<?php

namespace Wap\Controller;

use Common\Service\Alipay\aop\request\AlipaySystemOauthTokenRequest;
use Common\Service\Alipay\aop\AopClient;
use Think\Page;
use User\Model\FactoryModel;
use User\Model\MeetingModel;
use User\Model\RedPacketModel;
use Wap\Service\WechatService;
use Wap\Service\WeixinService;
use User\Model\ApplicationsModel;
use Wap\Model\StatisticsModel;

class ApplicationsController extends WapController
{
    public $wxTestToken;
    public $wxOfficialToken;
    public $wxTestUser;
    public $wxOfficialUser;
    private $_yuandan;
    private $_wennuanzhe;
    public $wxZLWDToken;
    public $wxGRZSToken;

    public function __construct()
    {
        parent::__construct();
        $this->wxTestToken = 'iequde1415960341';        //浙报新媒体
        $this->wxOfficialToken = 'wyirfc1427248117';    //浙报公益
        $this->wxZLWDToken = 'zuymbt1418285978';
        $this->wxGRZSToken = '21eb840870def11d6ef61fcf0cf60090';    //光荣浙商
        $this->handleCriteriaWxuser();
        $this->_yuandan = -11;
        $this->_wennuanzhe = -14;
        $this->_ant = -15;
        if ($_SERVER['HTTP_HOST'] == '192.168.1.137') {         //本地服务器
            $openid = get_client_ip();
            session("wennuanzhe_openid_" . $this->_wennuanzhe, $openid);
            session("wennuanzhe_nickname_" . $this->_wennuanzhe, $openid);
            session("ant_openid_" . $this->wxTestToken, $openid);
        }
    }

    //微信公众号信息
    private function handleCriteriaWxuser()
    {
        $this->wxTestUser = WeixinService::getWxuser($this->wxTestToken);
        $this->wxOfficialUser = WeixinService::getWxuser($this->wxOfficialToken);
    }

    //-----------------------------------JOIN项目开始----------------------------------------------
    public function joinIndex()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $this->display("Applications/join/index");
    }

    public function joinInvite()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $this->display("Applications/join/invite");
    }

    public function wxAuthJoin()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $id = I("get.id", -1, "");
        $openid = session("join_openid_" . $this->wxTestToken);
        if ($openid) {
            if ($id != -1) {
                redirect("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/joinInvite?id=" . $id . "&openid=" . $openid);
            } else {
                redirect("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/joinIndex?openid=" . $openid);
            }
        } else {
            $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
            $url = $wechat->buildOauthURI("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/wxAuthEntry?id=" . $id);
            redirect($url);
        }
    }

    public function wxAuthEntry()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $id = I("get.id", -1, "");
        $code = I("get.code", "", "");
        $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
        $openid = $wechat->snsapiBaseUser($code);
        session('join_openid_' . $this->wxTestToken, $openid);
        if ($id != -1) {
            $this->display("Applications/join/invite");
        } else {
            $this->display("Applications/join/index");
        }
    }

    public function getJoinByOpenid()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $openid = I("get.openid", "", "");
        if ($openid == '') {
            $this->ajaxReturn(array('status' => -1, 'msg' => '缺少参数openid'));
        }
        $join = M("join")->where(['openid' => $openid, 'status' => 1])->find();
        if (!empty($join)) {
            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'data' => array('id' => $join['id'])));
        } else {
            $this->ajaxReturn(array('status' => 3, 'msg' => 'empty'));
        }
    }

    public function getJoinById()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $id = I("get.id", -1, "");
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '缺少参数id'));
        }
        $join = M("join")->where(['id' => $id, 'status' => 1])->find();
        if (!empty($join)) {
            $list = M("join_record")->where(['join_id' => $id, 'status' => 1])->select();
            $data = array();
            if (!empty($list)) {
                foreach ($list as $key => $value) {
                    $data[] = array(
                        'id' => $value['record_id'],
                        'member_name' => $value['member_name'],
                        'head' => $value['head'],
                        'hair' => $value['hair'],
                        'cloth' => $value['cloth'],
                        'join_id' => $value['join_id'],
                        'openid' => $value['openid'],
                    );
                }
            }
            $join["list"] = $data;
            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'data' => $join));
        } else {
            $this->ajaxReturn(array('status' => 3, 'msg' => 'empty'));
        }
    }

    public function addJoinMember()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $openid = I("post.openid", "", "");
        $school = I("post.school", "", "");
        $class = I("post.class", "", "");
        $name = I("post.name", "", "");
        $head = I("post.head", "", "");
        $hair = I("post.hair", "", "");
        $cloth = I("post.cloth", "", "");
        $max_len = I("post.maxLen", "", "");
        $bg = I("post.bg", "", "");
        if ($openid == '' || $school == '' || $class == '' || $name == '' || $head == '' || $max_len == '' || $bg == ''
            || $hair == '' || $cloth == ''
        ) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '缺少参数'));
        }
        $ret = FactoryModel::ajaxImgUpload($head, 'join');
        if ($ret['code'] != 1) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '上传照片失败'));
        }
        $join = array(
            'openid' => $openid,
            'school' => $school,
            'class' => $class,
            'name' => $name,
            'max_len' => $max_len,
            'bg' => $bg
        );
        $added = M("join")->add($join);
        $record_id = 0;
        if ($added) {
            $record = array(
                'join_id' => $added,
                'openid' => $openid,
                'member_name' => $name,
                'head' => $ret['msg'],
                'hair' => $hair,
                'cloth' => $cloth
            );
            $record_id = M("join_record")->add($record);
        }
        if ($added && $record_id > 0) {
            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'data' => array('id' => $added)));
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => 'error'));
        }
    }

    public function makeJoin()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $id = I("post.id", -1, "");
        $photo = I("post.photo", "", "");
        if ($id == -1 || $photo == '') {
            $this->ajaxReturn(array('status' => -1, 'msg' => '缺少参数'));
        }
        $ret = FactoryModel::ajaxImgUpload($photo, 'join');
        if ($ret['code'] != 1) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '上传照片失败'));
        }
        $updated = M("join")->where(['id' => $id, 'status' => 1])->save(['photo' => $ret['msg']]);
        if ($updated) {
            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'data' => array('photo' => $ret['msg'])));
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => 'error'));
        }
    }

    public function addJoin()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $id = I("post.id", -1, "");
        $openid = I("post.openid", "", "");
        $member_name = I("post.member_name", "", "");
        $head = I("post.head", "", "");
        $hair = I("post.hair", "", "");
        $cloth = I("post.cloth", "", "");
        if ($id == -1 || $openid == '' || $member_name == '' || $head == '' || $hair == '' || $cloth == '') {
            $this->ajaxReturn(array('status' => -1, 'msg' => '缺少参数'));
        }
        $ret = FactoryModel::ajaxImgUpload($head, 'join');
        if ($ret['code'] != 1) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '上传照片失败'));
        }
        $record = array(
            'join_id' => $id,
            'openid' => $openid,
            'member_name' => $member_name,
            'head' => $ret['msg'],
            'hair' => $hair,
            'cloth' => $cloth
        );
        $added = M("join_record")->add($record);
        if ($added) {
            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'data' => array('id' => $id)));
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => 'error'));
        }
    }

    public function weixinShare()
    {
        $url = I("get.url", "", "");
        $wx = WeixinService::getWxuser($this->wxTestToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx, $url);
        if (!empty($wxJSApi)) {
            $data = array(
                'appId' => $wx['appid'],
                'nonceStr' => $wxJSApi['noncestr'],
                'wxTicket' => $wxJSApi['ticket'],
                'timestamp' => $wxJSApi['timestamp'],
                'signature' => $wxJSApi['sha1']
            );
            $this->ajaxReturn(array('status' => 1, 'appId' => $data['appId'], 'nonceStr' => $data['nonceStr'],
                'timestamp' => $data['timestamp'], 'signature' => $data['signature']));
        } else {
            $this->ajaxReturn(array('status' => -1, 'data' => 'empty'));
        }
    }
    //-----------------------------------JOIN项目结束----------------------------------------------

    //-----------------------------------差旅费报销查询项目开始-----------------------------------------------
    public function travelExpense()
    {
        $this->display("Applications/travelExpense/index");
    }

    public function getAreas()
    {
        $province = M("travel_expense")->where(['status' => 1])->field('id, province_code, province')
            ->group('province')->order('displayorder desc, id asc')->select();
        if (!empty($province)) {
            $codeArr = $district = $areas = $provinces = $area = $pro = array();
            foreach ($province as $value) {
                $pro[] = $value['province'];
                $provinces[] = array(
                    'province_code' => $value['province_code'],
                    'text' => $value['province'],
                    'value' => $value['id']
                );
                $codeArr[$value['province_code']] = $value['id'];
            }
            if (!empty($pro)) {
                $area = M("travel_expense")->where(['province' => array('in', $pro), 'status' => 1])
                    ->field('province_code, province, area')->group('province, area')
                    ->order('displayorder desc, id asc')->select();
                if (!empty($area)) {
                    foreach ($area as $value) {
                        $district[$value['province_code']][] = array('text' => $value['area']);
                    }
                    foreach ($codeArr as $key => $value) {
                        $areas[$value] = $district[$key];
                    }
                    if (!empty($provinces)) {
                        if (!empty($areas)) {
                            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'province' => $provinces, 'area' => $areas));
                        } else {
                            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'province' => $provinces));
                        }
                    } else {
                        $this->ajaxReturn(array('status' => 0, 'msg' => '暂无省市地区记录'));
                    }
                } else {
                    if (!empty($provinces)) {
                        $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'province' => $provinces));
                    } else {
                        $this->ajaxReturn(array('status' => 0, 'msg' => '暂无省市地区记录'));
                    }
                }
            } else {
                $this->ajaxReturn(array('status' => 0, 'msg' => '暂无省市地区记录'));
            }
        } else {
            $this->ajaxReturn(array('status' => 0, 'msg' => '暂无省市地区记录'));
        }
    }

    public function getTravelExpense()
    {
        $province = I("get.province", "", "");
        $area = I("get.area", "", "");
        $month = I("get.month", 0, "");
        if ($province == '' || $area == '' || $month == 0) {
            $this->ajaxReturn(array('status' => -1, 'msg' => '缺少参数'));
        }
        if ($province == '河南' && $area == '洛阳市' && $month == 5) {
            $type = 2;
            $expense = M("travel_expense")->where(['province' => $province, 'area' => $area, 'month' => $month, 'status' => 1])
                ->field('period, leader_expense, other_expense')->select();
        } else {
            $type = 1;
            $expense = M("travel_expense")->where(['province' => $province, 'area' => $area, 'month' => $month, 'status' => 1])
                ->field('leader_expense, other_expense')->find();
        }
        if (!empty($expense)) {
            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'type' => $type, 'data' => $expense));
        } else {
            $this->ajaxReturn(array('status' => 0, 'msg' => '暂无该地区月份记录'));
        }
    }

    public function expenseWxShare()
    {
        $url = I("get.url", "", "");
        $wx = WeixinService::getWxuser($this->wxTestToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx, $url);
        if (!empty($wxJSApi)) {
            $data = array(
                'appId' => $wx['appid'],
                'nonceStr' => $wxJSApi['noncestr'],
                'wxTicket' => $wxJSApi['ticket'],
                'timestamp' => $wxJSApi['timestamp'],
                'signature' => $wxJSApi['sha1']
            );
            $this->ajaxReturn(array('status' => 1, 'msg' => 'success', 'appId' => $data['appId'],
                'nonceStr' => $data['nonceStr'], 'timestamp' => $data['timestamp'], 'signature' => $data['signature']));
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => 'error, Invalid Signature'));
        }
    }
    //-----------------------------------差旅费报销查询项目结束----------------------------------------------

    //-----------------------------------人脸识别开始----------------------------------------------
    public function faceindex()
    {
        return $this->display('Applications/facego/index');
    }

    public function facecheck()
    {
        $result = array('code' => -1, 'msg' => '图片无法识别');
        $img = I("post.img", '', '');
        if (empty($img)) {
            $result['msg'] = '无图片数据';
            $this->ajaxReturn($result);
        }
        list($type, $data) = explode(',', $img);
        $ext = '';
        if (strstr($type, 'image/jpeg') != '') {
            $ext = '.jpeg';
        } elseif (strstr($type, 'image/png') != '') {
            $ext = '.png';
        } elseif (strstr($type, 'image/jpg') != '') {
            $ext = '.jpg';
        }
        if (empty($ext)) {
            $result['msg'] = '文件类型错误';
            $this->ajaxReturn($result);
        }
        Vendor("baidufacesdk.AipFace");
        $option = array(
            'max_face_num' => 1,
            'face_fields' => 'age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities'
        );
        $img = base64_decode($data);
        $face_result = '';
        for ($i = 0; $i < 3; $i++) {
            $rand = rand(0, 9);
            $baidu_face_array = array(
                array('app_id' => '10050796', 'api_secret' => 'uKZlRDMvgtyuVuvUeYDN7D2d', 'secret_key' => 'GYzzccZkh9aLsGm8rTnG1Gx8oTuoAQQB'),
                array('app_id' => '10050805', 'api_secret' => 'LGTGH6ikeMMFrrnQDxOcoUGw', 'secret_key' => 'lVzwtgluGVtLz2WlxmMS3WIMjEzuirYx'),
                array('app_id' => '10050811', 'api_secret' => 'wwxWZCExGWqPOz5TymXmtKOO', 'secret_key' => 'zfv2GBnrK0yNu1v9sfHHXzoahpurtwBY'),
                array('app_id' => '10050814', 'api_secret' => '8F2Fe6SmMtAhnw9fLrtowU1g', 'secret_key' => 'w189rZXMFmwSSQwybDy8ojGdY4AHjBHA'),
                array('app_id' => '10050821', 'api_secret' => 'DSE9vaY6XGIVZtXPQmylRME3', 'secret_key' => 'HOb4UqjfjHIx0RTKlTPZHWPNXvjvIphY'),
                array('app_id' => '10050825', 'api_secret' => 'sWlO5tQYT7yvHebCIcuOBLmd', 'secret_key' => 'dIeGdoaq4L9H5L0a3wx2vKElaXXsAV3i'),
                array('app_id' => '10050830', 'api_secret' => 'Pbdf6o369vib2jQHsGV3A3jL', 'secret_key' => 'k2qVqortKq0mor0GEaiNcbxKhwjqYgEh'),
                array('app_id' => '10050845', 'api_secret' => 'ogXtrdG7WGyFIWQ9owAOgAyj', 'secret_key' => 'FYkuZWPC2VhWMA0nqzTxNBqr6jSMMr3a'),
                array('app_id' => '10050849', 'api_secret' => 'FcE3GjYqLjpw2I5Exm2abYN1', 'secret_key' => 'Xbaw1KuZnyszPXGDoT4gE7pUHdoBG49F'),
                array('app_id' => '10050857', 'api_secret' => 'jbQwk8EiLa0GAHDaSd94mvaH', 'secret_key' => 'OkYS6HPqfLfjXfnwv63ff6IYRTI1cfT2')
            );;
            $baidu_face_info = $baidu_face_array[$rand];
            $apiFace = new \AipFace($baidu_face_info['app_id'], $baidu_face_info['api_secret'], $baidu_face_info['secret_key']);

            $face_result = @$apiFace->detect($img, $option);
            //--百度识别报错--
            if (isset($face_result['error_code']) || empty($face_result)) {
                continue;
            } else {
                break;
            }
        }
        if (isset($face_result['error_code']) || empty($face_result)) {
            $result['msg'] = isset($face_result['error_code']) ? $face_result['error_msg'] : "百度接口失败";
            $this->ajaxReturn($result);
        }
        //--未检测到人脸--
        if (!empty($face_result) && !empty($face_result['result_num'])) {
            if (($face_result['result']['0']['rotation_angle']) >= 10 || ($face_result['result']['0']['rotation_angle']) <= -10) {
                $result['msg'] = "人脸倾斜度过大";
                $this->ajaxReturn($result);
            } else {
                session('gender', $face_result['result']['0']['gender']);
                $result['code'] = 1;
                $result['msg'] = '成功';
                $source = imagecreatefromstring($img);
                $image = '';
                if ($face_result['result']['0']['gender'] == 'male') {
                    $image = imagerotate($source, $face_result['result']['0']['rotation_angle'] - 2, 0);
                } else {
                    $image = imagerotate($source, $face_result['result']['0']['rotation_angle'] + 3.5, 0);
                }
                $dir = "Public/Uploads/face/" . date('Ymd');
                if (!is_dir($dir)) mkdir($dir); // 如果不存在则创建
                $save_path = $dir;
                do {
                    $name = time() . rand(1, 1000000);
                    $save_path = $dir . "/" . $name . ".jpg";
                } while (file_exists($save_path));
                session('face_file', $save_path);
                imagejpeg($image, $save_path);
                imagedestroy($source);
                $this->ajaxReturn($result);
            }
        } else {
            $this->ajaxReturn($result);
        }
    }

    public function facego()
    {
        $rand = rand(0, 1000000);
        $img_array = array(
            array(
                'imge_url' => '/Public/projects/facego/face1.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face1background.jpg?v=' . $rand,
                'face_left' => 135,
                'face_top' => 135,
                'face_width' => 190,
                'face_height' => 210,
                'rotate' => 2.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face2.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face1background.jpg?v=' . $rand,
                'face_left' => 135,
                'face_top' => 135,
                'face_width' => 190,
                'face_height' => 210,
                'rotate' => 2.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face3.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face1background.jpg?v=' . $rand,
                'face_left' => 135,
                'face_top' => 135,
                'face_width' => 190,
                'face_height' => 210,
                'rotate' => 2.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face16.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face6background.jpg?v=' . $rand,
                'face_left' => 158,
                'face_top' => 110,
                'face_width' => 114,
                'face_height' => 130,
                'rotate' => 2.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face17.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face6background.jpg?v=' . $rand,
                'face_left' => 158,
                'face_top' => 110,
                'face_width' => 114,
                'face_height' => 130,
                'rotate' => 2.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face18.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face6background.jpg?v=' . $rand,
                'face_left' => 158,
                'face_top' => 110,
                'face_width' => 114,
                'face_height' => 130,
                'rotate' => 2.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face4.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face2background.jpg?v=' . $rand,
                'face_left' => 139,
                'face_top' => 136,
                'face_width' => 158,
                'face_height' => 148,
                'rotate' => 0.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face5.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face2background.jpg?v=' . $rand,
                'face_left' => 139,
                'face_top' => 136,
                'face_width' => 158,
                'face_height' => 148,
                'rotate' => 0.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face6.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face2background.jpg?v=' . $rand,
                'face_left' => 139,
                'face_top' => 136,
                'face_width' => 158,
                'face_height' => 148,
                'rotate' => 0.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face7.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face3background.jpg?v=' . $rand,
                'face_left' => 161,
                'face_top' => 122,
                'face_width' => 170,
                'face_height' => 190,
                'rotate' => 0.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face8.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face3background.jpg?v=' . $rand,
                'face_left' => 161,
                'face_top' => 122,
                'face_width' => 170,
                'face_height' => 190,
                'rotate' => 0.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face9.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face3background.jpg?v=' . $rand,
                'face_left' => 161,
                'face_top' => 122,
                'face_width' => 170,
                'face_height' => 190,
                'rotate' => 0.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face10.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face4background.jpg?v=' . $rand,
                'face_left' => 164,
                'face_top' => 125,
                'face_width' => 160,
                'face_height' => 170,
                'rotate' => 0
            ),
            array(
                'imge_url' => '/Public/projects/facego/face11.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face4background.jpg?v=' . $rand,
                'face_left' => 164,
                'face_top' => 125,
                'face_width' => 160,
                'face_height' => 170,
                'rotate' => 0
            ),
            array(
                'imge_url' => '/Public/projects/facego/face12.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face4background.jpg?v=' . $rand,
                'face_left' => 164,
                'face_top' => 125,
                'face_width' => 160,
                'face_height' => 170,
                'rotate' => 0
            ),
            array(
                'imge_url' => '/Public/projects/facego/face13.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face5background.jpg?v=' . $rand,
                'face_left' => 164,
                'face_top' => 162,
                'face_width' => 128,
                'face_height' => 133,
                'rotate' => 1.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face14.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face5background.jpg?v=' . $rand,
                'face_left' => 164,
                'face_top' => 162,
                'face_width' => 128,
                'face_height' => 133,
                'rotate' => 1.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face15.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face5background.jpg?v=' . $rand,
                'face_left' => 164,
                'face_top' => 162,
                'face_width' => 128,
                'face_height' => 133,
                'rotate' => 1.5
            ),
            array(
                'imge_url' => '/Public/projects/facego/face19.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face7background.jpg?v=' . $rand,
                'face_left' => 205,
                'face_top' => 107,
                'face_width' => 76,
                'face_height' => 80,
                'rotate' => 0
            ),
            array(
                'imge_url' => '/Public/projects/facego/face20.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face7background.jpg?v=' . $rand,
                'face_left' => 205,
                'face_top' => 107,
                'face_width' => 76,
                'face_height' => 80,
                'rotate' => 0
            ),
            array(
                'imge_url' => '/Public/projects/facego/face21.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face7background.jpg?v=' . $rand,
                'face_left' => 205,
                'face_top' => 107,
                'face_width' => 76,
                'face_height' => 80,
                'rotate' => 0
            ),
            array(
                'imge_url' => '/Public/projects/facego/face22.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face8background.jpg?v=' . $rand,
                'face_left' => 200.5,
                'face_top' => 99,
                'face_width' => 72,
                'face_height' => 75,
                'rotate' => 0
            ),
            array(
                'imge_url' => '/Public/projects/facego/face23.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face8background.jpg?v=' . $rand,
                'face_left' => 200.5,
                'face_top' => 99,
                'face_width' => 72,
                'face_height' => 75,
                'rotate' => 0
            ),
            array(
                'imge_url' => '/Public/projects/facego/face24.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face8background.jpg?v=' . $rand,
                'face_left' => 200.5,
                'face_top' => 99,
                'face_width' => 72,
                'face_height' => 75,
                'rotate' => 0
            )
        );
        $gender = session('gender');
        $rand1 = 0;
        if ($gender == 'male') {
            $rand1 = rand(18, 20);
        } else {
            $rand1 = rand(21, 23);
        }
        $img_data = $img_array[$rand1];
        $this->assign('img_data', $img_data);

        $path = session('face_file');
        $this->assign('face', '/' . $path);
        Vendor("baidufacesdk.AipFace");
        $option = array(
            'max_face_num' => 1,
            'face_fields' => 'age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities'
        );
        $face_result = '';
        for ($i = 0; $i < 3; $i++) {
            $rand = rand(0, 9);
            $baidu_face_array = array(
                array('app_id' => '10050796', 'api_secret' => 'uKZlRDMvgtyuVuvUeYDN7D2d', 'secret_key' => 'GYzzccZkh9aLsGm8rTnG1Gx8oTuoAQQB'),
                array('app_id' => '10050805', 'api_secret' => 'LGTGH6ikeMMFrrnQDxOcoUGw', 'secret_key' => 'lVzwtgluGVtLz2WlxmMS3WIMjEzuirYx'),
                array('app_id' => '10050811', 'api_secret' => 'wwxWZCExGWqPOz5TymXmtKOO', 'secret_key' => 'zfv2GBnrK0yNu1v9sfHHXzoahpurtwBY'),
                array('app_id' => '10050814', 'api_secret' => '8F2Fe6SmMtAhnw9fLrtowU1g', 'secret_key' => 'w189rZXMFmwSSQwybDy8ojGdY4AHjBHA'),
                array('app_id' => '10050821', 'api_secret' => 'DSE9vaY6XGIVZtXPQmylRME3', 'secret_key' => 'HOb4UqjfjHIx0RTKlTPZHWPNXvjvIphY'),
                array('app_id' => '10050825', 'api_secret' => 'sWlO5tQYT7yvHebCIcuOBLmd', 'secret_key' => 'dIeGdoaq4L9H5L0a3wx2vKElaXXsAV3i'),
                array('app_id' => '10050830', 'api_secret' => 'Pbdf6o369vib2jQHsGV3A3jL', 'secret_key' => 'k2qVqortKq0mor0GEaiNcbxKhwjqYgEh'),
                array('app_id' => '10050845', 'api_secret' => 'ogXtrdG7WGyFIWQ9owAOgAyj', 'secret_key' => 'FYkuZWPC2VhWMA0nqzTxNBqr6jSMMr3a'),
                array('app_id' => '10050849', 'api_secret' => 'FcE3GjYqLjpw2I5Exm2abYN1', 'secret_key' => 'Xbaw1KuZnyszPXGDoT4gE7pUHdoBG49F'),
                array('app_id' => '10050857', 'api_secret' => 'jbQwk8EiLa0GAHDaSd94mvaH', 'secret_key' => 'OkYS6HPqfLfjXfnwv63ff6IYRTI1cfT2')
            );;
            $baidu_face_info = $baidu_face_array[$rand];
            $apiFace = new \AipFace($baidu_face_info['app_id'], $baidu_face_info['api_secret'], $baidu_face_info['secret_key']);

            $face_result = @$apiFace->detect(file_get_contents($path), $option);
            //--百度识别报错--
            if (isset($face_result['error_code']) || empty($face_result)) {
                continue;
            } else {
                break;
            }
        }
        if (isset($face_result['error_code']) || empty($face_result)) {
            $this->assign('code', -2);
            return $this->display('Applications/Facego/test1');
        }
        //--未检测到人脸--
        if (!empty($face_result) && !empty($face_result['result_num'])) {
            $this->assign('code', 1);
            $this->assign('rotate', -($face_result['result'][0]['rotation_angle'] + $img_data['rotate']));
            $this->assign('landmark', $face_result['result'][0]['landmark72']);
            return $this->display('Applications/facego/test1');
        } else {
            $this->assign('code', -4);
            return $this->display('Applications/facego/test1');
        }
    }
    //-----------------------------------人脸识别结束----------------------------------------------

    //-----------------------------------浙江农村垃圾分类开始----------------------------------------------
    public function zjncljfl()
    {
        M('redpacket_upload')->where(['id' => 1])->setInc('reserve', 1);
        $count = M('redpacket_upload')->where(['id' => 1])->getField('reserve');
        $wx = WeixinService::getWxuser($this->wxOfficialToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $this->assign('wxConfig', $wxConfig);
        $this->assign('count', $count);
        $this->display('Applications/zjncljfl/index');
    }
    //-----------------------------------浙江农村垃圾分类结束----------------------------------------------

    //-----------------------------------杭州临安撤市换区H5开始----------------------------------------------
    public function linan()
    {
        M('redpacket_upload')->where(['id' => 2])->setInc('reserve', 1);
        $count = M('redpacket_upload')->where(['id' => 2])->getField('reserve');
        $wx = WeixinService::getWxuser($this->wxOfficialToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $this->assign('wxConfig', $wxConfig);
        $this->assign('count', $count);
        $this->display('Applications/linan/index');
    }
    //-----------------------------------杭州临安撤市换区H5结束----------------------------------------------

    //-----------------------------------杭州2017云栖小镇H5开始----------------------------------------------
    public function yunqiTown()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $yunqitown_id = 16;             //对应红包雨活动编号是20
        $openid = session("yunqitown_openid_" . $this->wxOfficialToken);
        if ($openid) {
            if (!$this->_checkYunqiFans()) {
                $this->_registerYunqiFans();
            }
            $wx = WeixinService::getWxuser($this->wxOfficialToken);
            $wxJSApi = WeixinService::buildWXJSApi($wx);
            $wxConfig = array(
                'appId' => $wx['appid'],
                'timestamp' => $wxJSApi['timestamp'],
                'nonceStr' => $wxJSApi['noncestr'],
                'signature' => $wxJSApi['sha1']
            );
            $redpacket = M('redpacket')->where(['id' => $yunqitown_id, 'status' => RedPacketModel::STATUS_ACTIVE])
                ->find();
            $wxShare = array(
                'share_title' => $redpacket['share_title'] ? $redpacket['share_title'] :
                    '限时抢！送你一张最脑洞云栖大会门票',
                'share_desc' => $redpacket['share_desc'] ? $redpacket['share_desc'] :
                    '10月11日-14日，我在云栖小镇等你',
                'share_link' => $redpacket['share_link'] ? $redpacket['share_link'] :
                    C('SITE_URL') . '/Wap/Applications/yunqiTown',
                'share_img' => $redpacket['share_img'] ? C('SITE_URL') . '/' . $redpacket['share_img'] :
                    C('SITE_URL') . '/Public/images/RedPacket/redpacket/img_share.png'
            );
            $this->assign('title', $redpacket['title']);
            $this->assign('wxConfig', $wxConfig);
            $this->assign('wxShare', $wxShare);
            $this->display('Applications/yunqitown/index');
        } else {
            $wechat = new \Wap\Service\WechatService($this->wxOfficialUser['appid'], $this->wxOfficialUser['appsecret']);
            $url = $wechat->buildOauthURI("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/yunqiEntry");
            redirect($url);
        }
    }

    public function yunqiEntry()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $yunqitown_id = 16;             //对应红包雨活动编号是20
        $code = I("get.code", "", "");
        $wechat = new \Wap\Service\WechatService($this->wxOfficialUser['appid'], $this->wxOfficialUser['appsecret']);
        $openid = $wechat->snsapiBaseUser($code);
        session('yunqitown_openid_' . $this->wxOfficialToken, $openid);
        $this->_registerYunqiFans();
        $wx = WeixinService::getWxuser($this->wxOfficialToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $redpacket = M('redpacket')->where(['id' => $yunqitown_id, 'status' => RedPacketModel::STATUS_ACTIVE])
            ->find();
        $wxShare = array(
            'share_title' => $redpacket['share_title'] ? $redpacket['share_title'] :
                '限时抢！送你一张最脑洞云栖大会门票',
            'share_desc' => $redpacket['share_desc'] ? $redpacket['share_desc'] :
                '10月11日-14日，我在云栖小镇等你',
            'share_link' => $redpacket['share_link'] ? $redpacket['share_link'] :
                C('SITE_URL') . '/Wap/Applications/yunqiTown',
            'share_img' => $redpacket['share_img'] ? C('SITE_URL') . '/' . $redpacket['share_img'] :
                C('SITE_URL') . '/Public/images/RedPacket/redpacket/img_share.png'
        );
        $this->assign('title', $redpacket['title']);
        $this->assign('wxConfig', $wxConfig);
        $this->assign('wxShare', $wxShare);
        $this->display('Applications/yunqitown/index');
    }

    private function _checkYunqiFans()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $yunqitown_id = 16;             //对应红包雨活动编号是20
        $openid = session("yunqitown_openid_" . $this->wxOfficialToken);
        $fans = M('redpacket_fans')->where(['pid' => $yunqitown_id, 'openid' => $openid, 'status' =>
            RedPacketModel::STATUS_ACTIVE])->find();
        if (!empty($fans)) {
            return true;
        } else {
            return false;
        }
    }

    private function _registerYunqiFans()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $yunqitown_id = 16;             //对应红包雨活动编号是20
        $openid = session("yunqitown_openid_" . $this->wxOfficialToken);
        $redpacket = M('redpacket')->where(['id' => $yunqitown_id, 'status' => RedPacketModel::STATUS_ACTIVE])->find();
        if (!empty($redpacket)) {
            $condition['pid'] = $yunqitown_id;
            $condition['token'] = $redpacket['token'];
            $condition['openid'] = $openid;
            $condition['status'] = RedPacketModel::STATUS_ACTIVE;
            $fans = M('redpacket_fans')->where($condition)->find();
            if (empty($fans)) {
                $data = array(
                    'token' => $redpacket['token'],
                    'pid' => $yunqitown_id,
                    'openid' => $openid
                );
                M('redpacket_fans')->add($data);
            }
        }
    }

    /*
     *  中奖：奖品是5张门票，中奖概率在后台设置
     */
    public function getYunqiAward()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $yunqitown_id = 16;             //对应红包雨活动编号是20
        //活动是否存在
        $redpacket = M('redpacket')->where(['id' => $yunqitown_id, 'status' => RedPacketModel::STATUS_ACTIVE])->find();
        if (empty($redpacket)) {
            $this->ajaxReturn(array('status' => -4, 'errMsg' => 'invalid redpacket'));
        }
        //奖品是否存在
        $redpacket_item = M('redpacket_item')->where(['redpacket_id' => $yunqitown_id, 'status' =>
            RedPacketModel::STATUS_ACTIVE])->find();
        if (empty($redpacket_item)) {
            $this->ajaxReturn(array('status' => -4, 'errMsg' => 'invalid redpacket'));
        }
        //是否在抽奖时间内
        if (!empty($redpacket)) {
            $start_time = strtotime($redpacket['startdate']);
            $end_time = strtotime($redpacket['enddate']);
            $now_time = time();
            if ($now_time < $start_time) {
                //$this->ajaxReturn(array('status' => -5, 'errMsg' => '活动未开始'));
            }
            if ($now_time > $end_time) {
                $this->ajaxReturn(array('status' => -6, 'errMsg' => '活动已结束'));
            }
        }
        $yunqitown_award_id = $redpacket_item['id'];
        $yunqitown_award_total = $redpacket_item['number'];

        $openid = session("yunqitown_openid_" . $this->wxOfficialToken);
        if (!$openid || $openid == '') {
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'openid missing'));
        }
        //不能超过5张
        $where_total['pid'] = $yunqitown_id;
        $where_total['award_id'] = $yunqitown_award_id;
        $where_total['zhongjiang'] = 1;
        $where_total['status'] = RedPacketModel::STATUS_ACTIVE;
        $zhongjiang_total = M('redpacket_fansaward')->where($where_total)->count();
        if ($zhongjiang_total >= $yunqitown_award_total) {
            $data = array(
                'token' => $redpacket['token'],
                'pid' => $yunqitown_id,
                'openid' => $openid,
                'award_id' => 0,
                'zhongjiang' => 9
            );
            M('redpacket_fansaward')->add($data);
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'no zhongjiang'));
        } else {
            if ($this->_yunqiCalculate($yunqitown_award_total, $redpacket_item['reserve'])) {
                $redpacket_fansaward = M("redpacket_fansaward");
                $redpacket_fansaward->startTrans();
                $data = array(
                    'token' => $redpacket['token'],
                    'pid' => $yunqitown_id,
                    'openid' => $openid,
                    'award_id' => $yunqitown_award_id,
                    'zhongjiang' => 2
                );
                M('redpacket_fansaward')->add($data);
                if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
                    $zhongjiang_total = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                        ->where($where_total)->count();
                } else {
                    $zhongjiang_total = M("redpacket_fansaward")->where($where_total)->count();
                }
                if ($zhongjiang_total > $yunqitown_award_total) {
                    $redpacket_fansaward->rollback();
                    $this->ajaxReturn(array('status' => -1, 'errMsg' => 'no zhongjiang'));
                }
                $redpacket_fansaward->commit();
                $this->ajaxReturn(array('status' => 1));
            } else {
                $data = array(
                    'token' => $redpacket['token'],
                    'pid' => $yunqitown_id,
                    'openid' => $openid,
                    'award_id' => 0,
                    'zhongjiang' => 9
                );
                M('redpacket_fansaward')->add($data);
                $this->ajaxReturn(array('status' => -1, 'errMsg' => 'no zhongjiang'));
            }
        }
    }

    private function _yunqiCalculate($range, $rate)
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        if ($range > 0 && $rate > 0) {
            $range = $rate * 100000;
            $random = rand(1, 10000000);
            if ($random <= $range) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function yunqiInfo()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $yunqitown_id = 16;             //对应红包雨活动编号是20
        $name = I('post.name', '', '');
        $phone = I('post.phone', '', '');
        if ($name == '') {
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'name missing'));
        }
        if ($phone == '') {
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'phone missing'));
        }
        $openid = session("yunqitown_openid_" . $this->wxOfficialToken);
        if ($openid) {
            if (!$this->_checkYunqiFans()) {
                $this->_registerYunqiFans();
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'invalid openid'));
            } else {
                //
                $fans = M('redpacket_fansaward')->where(['pid' => $yunqitown_id, 'openid' => $openid])
                    ->order('createdate desc')->find();
                M('redpacket_fans')->where(['pid' => $yunqitown_id, 'openid' => $openid])->save(array('name' => $name,
                    'phone' => $phone));
                //更改中奖状态
                $redpacket_item = M('redpacket_item')->where(['redpacket_id' => $yunqitown_id, 'status' =>
                    RedPacketModel::STATUS_ACTIVE])->find();
                $yunqitown_award_id = $redpacket_item['id'];
                $yunqitown_award_total = $redpacket_item['number'];

                $redpacket_fansaward = M("redpacket_fansaward");
                $redpacket_fansaward->startTrans();
                M('redpacket_fansaward')->where(['id' => $fans['id'], 'openid' => $openid])->save(array('zhongjiang' => 1));

                $where_total['pid'] = $yunqitown_id;
                $where_total['award_id'] = $yunqitown_award_id;
                $where_total['zhongjiang'] = 1;
                $where_total['status'] = RedPacketModel::STATUS_ACTIVE;
                if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
                    $zhongjiang_total = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                        ->where($where_total)->count();
                } else {
                    $zhongjiang_total = M("redpacket_fansaward")->where($where_total)->count();
                }
                if ($zhongjiang_total > $yunqitown_award_total) {
                    $redpacket_fansaward->rollback();
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => '奖品发完了'));
                }
                $redpacket_fansaward->commit();
                $this->ajaxReturn(array('status' => 1));
            }
        } else {
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'openid missing'));
        }
    }
    //-----------------------------------杭州2017云栖小镇H5结束----------------------------------------------

    //-----------------------------------省残联H5开始----------------------------------------------
    public function canlian()
    {
        M('redpacket_upload')->where(['id' => 3])->setInc('reserve', 1);
        $count = M('redpacket_upload')->where(['id' => 3])->getField('reserve');
        $wx = WeixinService::getWxuser($this->wxOfficialToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $this->assign('wxConfig', $wxConfig);
        $this->assign('count', $count);
        $this->display('Applications/canlian/index');
    }

    //-----------------------------------省残联H5结束----------------------------------------------
    public function uploadVoice()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->rootPath = './Public/Uploads/wx/voice/'; // 设置附件上传根目录
        $upload->subName = array("date", "Ymd");
        $upload->saveName = array("uniqid", "voice");
        // 上传文件
        trace("test11", "zjdailycard", "SQL", true);
        trace($_FILES, "zjdailycard1", "SQL", true);
        $info = $upload->upload();
        $field1 = '';
        if ($info) {
            foreach ($info as $key => $file) {
                $field1 = "http://" . $_SERVER["HTTP_HOST"] . '/Public/Uploads/wx/voice/' . date('Ymd') . "/" . $file['savename'];
            }
        }
        $id = 0;
        if ($field1) {
            $data['field1'] = $field1;
            $id = M("test")->add($data);
        }
        $this->ajaxReturn($field1);
    }

    public function meeting_login()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        return $this->display("Applications/meeting/login");
    }

    public function meeting_check()
    {
        $cond['email'] = trim(I("post.user_name", "", ""));
        $cond['password'] = md5(trim(I("post.passwd", "", "")));
        $user = M("users")->where($cond)->find();
        if (!empty($user)) {
            session("user_login_open_id", $user['openid']);
            $now = time();
            M("users")->where(array('id' => $user['id']))->save(array('lasttime' => $now, 'lastip' => htmlspecialchars(trim(get_client_ip()))));
            $this->ajaxReturn(['code' => true]);
        } else {
            $this->ajaxReturn(['code' => false]);
        }
    }

    public function meeting_activity()
    {
        $session_open_id = session("user_login_open_id");
        if (empty($session_open_id)) {
            return $this->redirect("/Wap/Applications/meeting_login");
        }
        $cond['status'] = MeetingModel::STATUS_ACTIVE;
        $cond['openid'] = $session_open_id;
        $meeting = M("meeting")->where($cond)->order("meet_id desc")->select();
        $this->assign("meeting", $meeting);
        return $this->display("Applications/meeting/activity");
    }

    public function meeting_ajax()
    {
        $cond['status'] = MeetingModel::STATUS_ACTIVE;
        $session_open_id = session("user_login_open_id");
        $cond['openid'] = $session_open_id;
        $page = I("get.page", 0, "");
        $first_row = $page * 1;
        $meeting = M("meeting")->where($cond)->limit($first_row, 1)->order("meet_id desc")->select();
        $this->ajaxReturn($meeting);
    }

    //-----------------------------------滨江新地标H5开始----------------------------------------------
    public function bjxdb()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $where["id"] = 4;
        M('redpacket_upload')->where($where)->setInc('reserve', 1);
        $count = M('redpacket_upload')->where($where)->getField('reserve');
        $wx = WeixinService::getWxuser($this->wxOfficialToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $this->assign('wxConfig', $wxConfig);
        $this->assign('count', $count);
        $this->display('Applications/bjxdb/index');
    }
    //-----------------------------------滨江新地标H5结束----------------------------------------------

    //-----------------------------------元旦祝福H5结束----------------------------------------------
    public function yuandan()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        if ($_SERVER['HTTP_HOST'] == '192.168.1.137') {         //本地服务器
            $openid = get_client_ip();
            session('yuandan_openid_' . $this->_yuandan, $openid);
        }
        $id = I("get.id", -1, "");
        $uid = I("get.uid", -1, "");
        $to = I("get.to", "", "");
        $code = I("get.code", "", "");
        $openid = session("yuandan_openid_" . $this->_yuandan);
        if (!empty($openid)) {
            $self_uid = $this->_registerUser();
            if ($id != -1) {
                if ($uid == $self_uid) {
                    //自己打开
                    redirect("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/yuandan#/launch");
                } else {
                    //别人打开
                    $this->_registerWish($id, $self_uid);
                }
            }
            $wxJSApi = WeixinService::buildWXJSApi($this->wxTestUser);
            $wxConfig = array(
                'appId' => $this->wxTestUser['appid'],
                'timestamp' => $wxJSApi['timestamp'],
                'nonceStr' => $wxJSApi['noncestr'],
                'signature' => $wxJSApi['sha1']
            );
            $shareData = array(
                'share_title' => "2018有你祝福才幸福，跨年祝福不群发，快来！",
                'share_desc' => "送出你的专属祝福，生成你的专属幸福！",
                'share_image' => C("SITE_URL") . "/Public/images/share_yuandan.jpg",
                'share_link' => C("SITE_URL") . "/Wap/Applications/yuandan#/launch"
            );
            $this->assign("wxConfig", $wxConfig);
            $this->assign("shareData", $shareData);
            StatisticsModel::visit("yuandan", 1);
            $where_count['topic_id'] = $this->_yuandan;
            $where_count['msg_type'] = ApplicationsModel::TYPE_RECEIVE;
            $where_count['comment_id'] = $self_uid;
            $where_count['status'] = ApplicationsModel::STATUS_ACTIVE;
            $count = M("live_comment")->where($where_count)->count();
            $this->assign("count", $count);
            $this->assign("uid", $self_uid);
            $this->display('Applications/yuandan/index');
        } else {
            $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
            if ($code) {
                $out = $wechat->snsapiUserInfo($this->wxTestUser['appid'], $this->wxTestUser['appsecret'], $code);
                if ($out != null) {
                    session("yuandan_openid_" . $this->_yuandan, $out['openid']);
                    session("yuandan_nickname_" . $this->_yuandan, $out['nickname']);
                    session("yuandan_headimgurl_" . $this->_yuandan, $out['headimgurl']);
                }
                $self_uid = $this->_registerUser();
                if ($id != -1) {
                    if ($uid == $self_uid) {
                        //自己打开
                        redirect("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/yuandan#/launch");
                    } else {
                        //别人打开
                        $this->_registerWish($id, $self_uid);
                    }
                }
                $wxJSApi = WeixinService::buildWXJSApi($this->wxTestUser);
                $wxConfig = array(
                    'appId' => $this->wxTestUser['appid'],
                    'timestamp' => $wxJSApi['timestamp'],
                    'nonceStr' => $wxJSApi['noncestr'],
                    'signature' => $wxJSApi['sha1']
                );
                $shareData = array(
                    'share_title' => "2018有你祝福才幸福，跨年祝福不群发，快来！",
                    'share_desc' => "送出你的专属祝福，生成你的专属幸福！",
                    'share_image' => C("SITE_URL") . "/Public/images/share_yuandan.jpg",
                    'share_link' => C("SITE_URL") . "/Wap/Applications/yuandan#/launch"
                );
                $this->assign("wxConfig", $wxConfig);
                $this->assign("shareData", $shareData);
                StatisticsModel::visit("yuandan", 1);
                $where_count['topic_id'] = $this->_yuandan;
                $where_count['msg_type'] = ApplicationsModel::TYPE_RECEIVE;
                $where_count['comment_id'] = $self_uid;
                $where_count['status'] = ApplicationsModel::STATUS_ACTIVE;
                $count = M("live_comment")->where($where_count)->count();
                $this->assign("count", $count);
                $this->assign("uid", $self_uid);
                $this->display('Applications/yuandan/index');
            } else {
                if ($to == "wall") {
                    if ($uid != -1) {
                        if ($id != -1) {
                            $uri = "http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/yuandan?to=wall&uid=" . $uid .
                                "&id=" . $id;
                        } else {
                            $uri = "http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/yuandan?to=wall&uid=" . $uid;
                        }
                    } else {
                        $uri = "http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/yuandan#/launch";
                    }
                } else {
                    $uri = "http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/yuandan#/launch";
                }
                $url = $wechat->snsapiUserInfoLink($uri, $this->wxTestUser['appid']);
                redirect($url);
            }
        }
    }

    private function _registerUser()
    {
        $uid = 0;
        $openid = session("yuandan_openid_" . $this->_yuandan);
        $nickname = session("yuandan_nickname_" . $this->_yuandan);
        $avatar = session("yuandan_headimgurl_" . $this->_yuandan);
        if ($openid) {
            $where['questionnaire_id'] = $this->_yuandan;
            $where['openid'] = session("yuandan_openid_" . $this->_yuandan);
            $where['status'] = ApplicationsModel::USER_ACTIVE;
            $user = M("questionnaire_fans")->where($where)->find();
            $uid = $user["id"];
            if (!empty($user)) {
                $where_fans['id'] = $uid;
                if ($user["nickname"] == "") {
                    $nickname = json_encode($nickname);
                    M("questionnaire_fans")->where($where_fans)->save(array("nickname" => $nickname));
                }
                if ($user["reserve"] == "") {
                    M("questionnaire_fans")->where($where_fans)->save(array("reserve" => $avatar));
                }
            } else {
                $data = array(
                    'questionnaire_id' => $this->_yuandan,
                    'openid' => $openid,
                    'nickname' => json_encode($nickname),
                    'reserve' => $avatar
                );
                $uid = M("questionnaire_fans")->add($data);
            }
        }
        return $uid;
    }

    private function _registerWish($id, $self_uid)
    {
        $where["id"] = $id;
        $where["status"] = ApplicationsModel::STATUS_ACTIVE;
        $yuandan_comment = M("live_comment")->where($where)->find();
        if (!empty($yuandan_comment)) {
            //防止重新插入一遍
            $where_register["chat_id"] = $id;
            $where_register["comment_id"] = $self_uid;
            $where_register["status"] = ApplicationsModel::STATUS_ACTIVE;
            $register_comment = M("live_comment")->where($where_register)->find();
            if (empty($register_comment)) {
                $data = array(
                    'openid' => $yuandan_comment["openid"],
                    'topic_id' => $this->_yuandan,
                    'chat_id' => $id,
                    'content' => $yuandan_comment["content"],
                    'comment_type' => $yuandan_comment["comment_type"],
                    'msg_type' => ApplicationsModel::TYPE_RECEIVE,
                    'comment_id' => $self_uid,
                    'reserve' => $this->wxTestToken
                );
                M("live_comment")->add($data);
            }
        }
    }

    public function sendTxt()
    {
        $content = I("get.content", "", "");
        if ($content == "") {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "content missing"));
        }
        $openid = session("yuandan_openid_" . $this->_yuandan);
        if ($openid) {
            $data = array(
                'openid' => $openid,
                'topic_id' => $this->_yuandan,
                'content' => json_encode(htmlspecialchars($content)),
                'comment_type' => ApplicationsModel::WISH_TXT,
                'msg_type' => ApplicationsModel::TYPE_SEND,
                'reserve' => $this->wxTestToken
            );
            $id = M("live_comment")->add($data);
            $this->ajaxReturn(array("status" => 1, "id" => $id));
        } else {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "openid missing"));
        }
    }

    public function sendVoice()
    {
        $content = I("post.content", "", "");
        $record_time = I("post.record_time", 0, "");
        if ($content == "") {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "content missing"));
        }
        if ($record_time == 0) {
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'record time missing'));
        }
        $openid = session("yuandan_openid_" . $this->_yuandan);
        if ($openid) {
            $media = $this->_downloadWxFile($content);
            if ($media != "") {
                $content = array(
                    'media' => $media,
                    'record_time' => $record_time,
                    'serverId' => $content
                );
                $content = json_encode($content);
                $data = array(
                    'openid' => $openid,
                    'topic_id' => $this->_yuandan,
                    'content' => $content,
                    'comment_type' => ApplicationsModel::WISH_VOICE,
                    'msg_type' => ApplicationsModel::TYPE_SEND,
                    'reserve' => $this->wxTestToken
                );
                $id = M("live_comment")->add($data);
                $this->ajaxReturn(array("status" => 1, "id" => $id));
            } else {
                $this->ajaxReturn(array("status" => -3, "errMsg" => "server error"));
            }
        } else {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "openid missing"));
        }
    }

    public function receiveTxt()
    {
        $uid = I("post.uid", -1, "");
        $content = I("post.content", "", "");
        if ($uid == -1) {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "uid missing"));
        }
        if ($content == "") {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "content missing"));
        }
        $openid = session("yuandan_openid_" . $this->_yuandan);
        if ($openid) {
            $data = array(
                'openid' => $openid,
                'topic_id' => $this->_yuandan,
                'content' => json_encode(htmlspecialchars($content)),
                'comment_type' => ApplicationsModel::WISH_TXT,
                'msg_type' => ApplicationsModel::TYPE_RECEIVE,
                'comment_id' => $uid,
                'reserve' => $this->wxTestToken
            );
            M("live_comment")->add($data);
            $this->ajaxReturn(array("status" => 1));
        } else {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "openid missing"));
        }
    }

    public function receiveVoice()
    {
        $uid = I("post.uid", -1, "");
        $content = I("post.content", "", "");
        $record_time = I("post.record_time", 0, "");
        if ($uid == -1) {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "uid missing"));
        }
        if ($content == "") {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "content missing"));
        }
        if ($record_time == 0) {
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'record time missing'));
        }
        $openid = session("yuandan_openid_" . $this->_yuandan);
        if ($openid) {
            $media = $this->_downloadWxFile($content);
            if ($media != "") {
                $content = array(
                    'media' => $media,
                    'record_time' => $record_time,
                    'serverId' => $content
                );
                $content = json_encode($content);
                $data = array(
                    'openid' => $openid,
                    'topic_id' => $this->_yuandan,
                    'content' => $content,
                    'comment_type' => ApplicationsModel::WISH_VOICE,
                    'msg_type' => ApplicationsModel::TYPE_RECEIVE,
                    'comment_id' => $uid,
                    'reserve' => $this->wxTestToken
                );
                M("live_comment")->add($data);
                $this->ajaxReturn(array("status" => 1));
            } else {
                $this->ajaxReturn(array("status" => -3, "errMsg" => "server error"));
            }
        } else {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "openid missing"));
        }
    }

    public function getWishList()
    {
        $uid = I("get.uid", -1, "");
        $id = I("get.id", -1, "");
        $page = I("get.page", 0, "");
        if ($uid == -1) {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "uid missing"));
        }
        $openid = session("yuandan_openid_" . $this->_yuandan);
        $where_user["id"] = $uid;
        $where_user["questionnaire_id"] = $this->_yuandan;
        $where_user["status"] = ApplicationsModel::USER_ACTIVE;
        $user = M("questionnaire_fans")->where($where_user)->find();
        $where_user_self["openid"] = $openid;
        $where_user_self["questionnaire_id"] = $this->_yuandan;
        $where_user_self["status"] = ApplicationsModel::USER_ACTIVE;
        $user_self = M("questionnaire_fans")->where($where_user_self)->find();
        if (!empty($user)) {
            $where_comment["topic_id"] = $this->_yuandan;
            $where_comment["msg_type"] = ApplicationsModel::TYPE_RECEIVE;
            $where_comment["comment_id"] = ($id != -1) ? $user_self['id'] : $uid;
            $where_comment["status"] = ApplicationsModel::STATUS_ACTIVE;
            $where_comment["reserve"] = $this->wxTestToken;
            if ($page >= 1) {
                $page = $page * 20;
            } else {
                $page = 0;
            }
            $yuandan_comment = M("live_comment")->where($where_comment)->order("id desc")->limit($page . ", 20")
                ->select();
            $count = M("live_comment")->where($where_comment)->order("id desc")->count();
            $list = $fans = $avatars = array();
            if (!empty($yuandan_comment)) {
                foreach ($yuandan_comment as $com) {
                    $fans[] = $com["openid"];
                }
                $fans = array_flip(array_flip($fans));
                $where_fans["openid"] = array("IN", $fans);
                $where_fans["questionnaire_id"] = $this->_yuandan;
                $where_fans["status"] = ApplicationsModel::USER_ACTIVE;
                $yuandan_fans = M("questionnaire_fans")->where($where_fans)->select();
                if (!empty($yuandan_fans)) {
                    foreach ($yuandan_fans as $fa) {
                        $avatars[$fa["openid"]] = $fa["reserve"];
                    }
                }
                foreach ($yuandan_comment as $value) {
                    if ($value["comment_type"] == ApplicationsModel::WISH_TXT) {
                        $txt = json_decode($value["content"], true);
                        $voice = "";
                        $record_time = 0;
                    } else {
                        $txt = "";
                        $content = json_decode($value["content"], true);
                        $voice = C("SITE_URL") . $content["media"];
                        $record_time = $content["record_time"];
                    }
                    $list[] = array(
                        'avatar' => $avatars[$value['openid']],
                        'comment_type' => $value["comment_type"],
                        'txt' => $txt,
                        'voice' => $voice,
                        'record_time' => $record_time,
                    );
                }
            }
            $nickname = json_decode($user["nickname"], true);
            $nickname_self = json_decode($user_self["nickname"], true);
            if ($id != -1) {
                $title = $nickname . "为你送上了一份新年祝福，快来查收吧....";
                $this->ajaxReturn(array("status" => 1, "title" => $title, "self" => 1, "nickname" => $nickname_self,
                    "count" => $count, "list" => $list));
            } else {
                $title = "有什么要对我说的话吗？不要犹豫，趁现在吧！";
                if ($openid == $user["openid"]) {
                    $this->ajaxReturn(array("status" => 1, "title" => $title, "self" => 1, "nickname" => $nickname,
                        "count" => $count, "list" => $list));
                } else {
                    $this->ajaxReturn(array("status" => 1, "title" => $title, "self" => 0, "nickname" => $nickname,
                        "count" => $count, "list" => $list));
                }
            }
        } else {
            $nickname = "游客";
            $this->ajaxReturn(array("status" => 1, "self" => 0, "nickname" => $nickname, "count" => 0,
                "list" => array()));
        }
    }

    public function getShareSend()
    {
        $id = I("get.id", -1, "");
        if ($id == -1) {
            $this->ajaxReturn(array("status" => -1, "errMsg" => "id missing"));
        }
        $uid = $this->_registerUser();
        $where["id"] = $uid;
        $nickname_send = M("questionnaire_fans")->where($where)->getField("nickname");
        if ($nickname_send != null) {
            $nickname_send = json_decode($nickname_send, true);
        }
        $share_send = array(
            'share_title' => $nickname_send . "为你送上了一份新年祝福，快来查收吧....",
            'share_desc' => "2018最想对你说的话都在这里了...",
            'share_image' => C("SITE_URL") . "/Public/images/share_yuandan.jpg",
            'share_link' => C("SITE_URL") . "/Wap/Applications/yuandan?to=wall&uid=" . $uid . "&id=" . $id
        );
        $this->ajaxReturn(array("status" => 1, "shareSend" => $share_send));
    }

    public function getShareReceive()
    {
        $uid = $this->_registerUser();
        $share_receive = array(
            'share_title' => "有什么要对我说的话吗？不要犹豫，趁现在吧！",
            'share_desc' => "2018群发的祝福我不收，快来为我定制新年祝福吧！！！",
            'share_image' => C("SITE_URL") . "/Public/images/share_yuandan.jpg",
            'share_link' => C("SITE_URL") . "/Wap/Applications/yuandan?to=wall&uid=" . $uid
        );
        $this->ajaxReturn(array("status" => 1, "shareReceive" => $share_receive));
    }

    public function token()
    {
        $token = $this->_getAccessToken();
        echo $token;
    }

    //下载并保存微信服务器amr音频文件
    private function _downloadWxFile($media_id)
    {
        $token = $this->_getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=' . $token . '&media_id=' . $media_id;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);

        $prefix = explode("/", $httpinfo["content_type"]);
        $time = time();
        $filename = $time . "." . $prefix[1];
        $new_filename = $time . ".mp3";
        $dir = 'Public/Uploads/yuandan/' . date('Ymd');
        if (!is_dir($dir)) mkdir($dir);
        $local_file = fopen("Public/Uploads/yuandan/" . date('Ymd') . '/' . $filename, 'w');
        fwrite($local_file, $package);
        fclose($local_file);

        //ffmpeg amr转码成mp3
        if ($_SERVER['HTTP_HOST'] == 'www.zjdaily.org') {
            $path_amr = '/home/www/zjdaily/trunk/Public/Uploads/yuandan/' . date('Ymd') . '/' . $filename;
            $path_mp3 = '/home/www/zjdaily/trunk/Public/Uploads/yuandan/' . date('Ymd') . '/' . $new_filename;
        } else {
            $path_amr = '/home/www/esm.zbxinmeiti.com/zjdaily/trunk/Public/Uploads/yuandan/' . date('Ymd') .
                '/' . $filename;
            $path_mp3 = '/home/www/esm.zbxinmeiti.com/zjdaily/trunk/Public/Uploads/yuandan/' . date('Ymd') .
                '/' . $new_filename;
        }
        exec('/usr/local/bin/ffmpeg -i ' . $path_amr . ' ' . $path_mp3);
        $media_url = '/Public/Uploads/yuandan/' . date('Ymd') . '/' . $new_filename;

        return $media_url;
    }

    private function _getAccessToken()
    {
        $access_token = S('yuandan_access_token_' . $this->wxTestUser['token']);
        if (!$access_token) {
            $url_get = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' .
                $this->wxTestUser['appid'] . '&secret=' . $this->wxTestUser['appsecret'];
            $json = json_decode($this->_curlGet($url_get));
            if (!$json->errmsg) {
                $access_token = $json->access_token;
                S('yuandan_access_token_' . $this->wxTestUser['token'], $access_token, 6300);
            } else {
                $this->error('获取access_token发生错误：错误代码' . $json->errcode .
                    ',微信返回错误信息：' . $json->errmsg);
            }
        }
        return $access_token;
    }

    private function _curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    //审核页面
    public function yuandan_check()
    {
        $mode = 1;      //登录页面
        if (IS_POST || (session("yuandan_check_login_in") == 1)) {
            if ((session("yuandan_check_login_in") != 1)) {
                $password = I("post.password", "", "");
                if ($password == "") {
                    $this->error("密码不能为空");
                }
                if ($password != 85312349) {
                    $this->error("密码错误");
                }
                session("yuandan_check_login_in", 1);
            }
            $mode = 2;  //祝福语页面
            $live_comment = M("live_comment");
            $where_son1["comment_id"] = 0;
            $where_son1["msg_type"] = ApplicationsModel::TYPE_SEND;
            $where_son2["chat_id"] = 0;
            $where_son2["comment_id"] = array("neq", 0);
            $where_son2["msg_type"] = ApplicationsModel::TYPE_RECEIVE;
            $where_main['_complex'] = array(
                $where_son1,
                $where_son2,
                '_logic' => 'or'
            );
            $where_main["topic_id"] = $this->_yuandan;
            $where_main["status"] = ApplicationsModel::STATUS_ACTIVE;
            $where_main["reserve"] = $this->wxTestToken;
            $count = $live_comment->where($where_main)->count();
            $page = new Page($count, 50);
            $show = $page->show();

            $list = $live_comment->where($where_main)->limit($page->firstRow . "," . $page->listRows)
                ->order("id desc")->select();
            $user = $fans = array();
            if (!empty($list)) {
                foreach ($list as &$value) {
                    if ($value["comment_type"] == ApplicationsModel::WISH_TXT) {
                        $value["content"] = json_decode($value["content"], true);
                    } else {
                        $content = json_decode($value["content"], true);
                        $value["content"] = C("SITE_URL") . $content["media"];
                        $value["record_time"] = $content["record_time"];
                    }
                    $value["createdate"] = date("m-d H:i:s", strtotime($value["createdate"]));
                    $user[] = $value["openid"];
                }
                $user = array_flip(array_flip($user));
                if (!empty($user)) {
                    $where_fans["openid"] = array("IN", $user);
                    $where_fans["questionnaire_id"] = $this->_yuandan;
                    $where_fans["status"] = ApplicationsModel::USER_ACTIVE;
                    $questionnaire_fans = M("questionnaire_fans")->where($where_fans)->select();
                    if (!empty($questionnaire_fans)) {
                        foreach ($questionnaire_fans as $fa) {
                            $fans[$fa["openid"]] = json_decode($fa["nickname"], true);
                        }
                    }
                }
            }
            $this->assign("page", $show);
            $this->assign("list", $list);
            $this->assign("fans", $fans);
        }
        $this->assign("mode", $mode);
        $this->display("Applications/yuandan/check");
    }

    public function deleteComment()
    {
        $id = I("get.id", -1, "");
        $where['id'] = $id;
        $updated = M("live_comment")->where($where)->save(array("status" => ApplicationsModel::STATUS_DELETE));
        //删除扩散的数据
        $where_send['chat_id'] = $id;
        $updated_send = M("live_comment")->where($where_send)->save(array("status" => ApplicationsModel::STATUS_DELETE));
        if ($updated !== false) {
            $this->success("删除成功", "", true);
        } else {
            $this->success("删除失败", "", true);
        }
    }
    //-----------------------------------元旦祝福H5结束----------------------------------------------

    //-----------------------------------年货地图H5开始----------------------------------------------
    public function nhdt()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $where["id"] = 5;
        M('redpacket_upload')->where($where)->setInc('reserve', 1);
        $count = M('redpacket_upload')->where($where)->getField('reserve');
        $wx = WeixinService::getWxuser($this->wxOfficialToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $wxShareData = array(
            'share_title' => "“浙”里过大年",
            'share_desc' => "“浙”里最全面的年货地图出炉啦！我是第" . $count . "个民俗文化传播者",
            'share_link' => C('SITE_URL') . '/Wap/Applications/nhdt',
            'share_image' => C("SITE_URL") . "/Public/projects/nhdt/images/share.png",
        );
        $this->assign('wxConfig', $wxConfig);
        $this->assign('wxShareData', $wxShareData);
        $this->display('Applications/nhdt/index');
    }
    //-----------------------------------年货地图H5结束----------------------------------------------

    //-----------------------------------浙江疗养评选H5开始----------------------------------------------
    public function zjlypx()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $wx = WeixinService::getWxuser($this->wxOfficialToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $wxShareData = array(
            'share_title' => "2018浙江全域疗休养评选活动",
            'share_desc' => "发现浙江疗休养圣地，打造疗休养新玩法",
            'share_link' => C('SITE_URL') . '/Wap/Applications/zjlypx',
            'share_image' => C("SITE_URL") . "/Public/projects/zjlypx/images/share_zjly.jpg"
        );
        $this->assign('wxConfig', $wxConfig);
        $this->assign('wxShareData', $wxShareData);
        $this->display('Applications/zjlypx/index');
    }
    //-----------------------------------浙江疗养评选H5结束----------------------------------------------

    //----人生----
    public function rsindex()
    {
        $cond['id'] = 1;
        $res = M("data_important")->where($cond)->find();
        $this->assign("like", $res['rensheng_like']);

        $data['rensheng_view'] = $res['rensheng_view'] + 1;
        $this->assign("view", $data['rensheng_view']);
        M("data_important")->where($cond)->save($data);
        $this->display("Applications/rsindex/index1");
    }

    public function rensheng()
    {
        $type = $_POST['type'];
        $id = $_POST['id'];

        if (isset($_COOKIE['likeDislike' . "_" . $id]))
            echo "   ";
        else {
            if ($type == 'like') {
                $fieldName = 'pLike';
            } elseif ($type == 'dislike') {
                $fieldName = 'pDislike';
            } else {
                die();
            }
            $cond['id'] = 1;
            $count = M("data_important")->where($cond)->getField("rensheng_like");
            $data['rensheng_like'] = $count + 1;
            M("data_important")->where($cond)->save($data);
            $expire = time() + 60 * 60 * 24 * 30;
            setcookie("likeDislike" . "_" . $id, "likeDislike" . "_" . $id, $expire);
            echo "success||" . $data['rensheng_like'];
        }
    }
    //----人生结束----

    //---安全举报功能开始---
    public function tip()
    {
        $wx = WeixinService::getWxuser($this->wxZLWDToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        if (!empty($wxJSApi)) {
            $this->assign("appId", $wx['appid']);
            $this->assign("nonceStr", $wxJSApi['noncestr']);
            $this->assign("timestamp", $wxJSApi['timestamp']);
            $this->assign("wxsha1", $wxJSApi['sha1']);
        }
        return $this->display("Applications/tip/index");
    }

    public function tipAjax()
    {
        $data['content'] = I("post.content", "", "");
        if ($data['content'] == '') {
            $this->ajaxReturn(['msg' => "请输入举报内容"]);
        }
        $data['company'] = I("post.company", "", "");
        if ($data['company'] == '') {
            $this->ajaxReturn(['msg' => "请输入单位"]);
        }
        $data['name'] = I("post.name", "", "");
        if ($data['name'] == '') {
            $this->ajaxReturn(['msg' => "请输入姓名"]);
        }
        $data['telephone'] = I("post.telephone", "", "");
        if ($data['telephone'] == '') {
            $this->ajaxReturn(['msg' => "请输入电话"]);
        }
        $pic = I("post.pic", "", "");
        $data['type'] = 1;
        $res = FactoryModel::ajaxImgUploadThumb($pic, "tip", 400);
        if ($res['code'] == 1) {
            $data['pic'] = $res['msg'];
        }
        M("tip")->add($data);
        $this->ajaxReturn(["msg" => "已成功"]);
    }
    //---安全举报功能结束---

    //---民意直通车开始---
    public function suggest()
    {
        $wx = WeixinService::getWxuser($this->wxZLWDToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        if (!empty($wxJSApi)) {
            $this->assign("appId", $wx['appid']);
            $this->assign("nonceStr", $wxJSApi['noncestr']);
            $this->assign("timestamp", $wxJSApi['timestamp']);
            $this->assign("wxsha1", $wxJSApi['sha1']);
        }
        return $this->display("Applications/suggest/index");
    }

    public function suggestAjax()
    {
        $data['content'] = I("post.content", "", "");
        if ($data['content'] == '') {
            $this->ajaxReturn(['msg' => "意见内容"]);
        }
        $data['company'] = I("post.company", "", "");
        if ($data['company'] == '') {
            $this->ajaxReturn(['msg' => "请输入单位"]);
        }
        $data['name'] = I("post.name", "", "");
        if ($data['name'] == '') {
            $this->ajaxReturn(['msg' => "请输入姓名"]);
        }
        $data['telephone'] = I("post.telephone", "", "");
        if ($data['telephone'] == '') {
            $this->ajaxReturn(['msg' => "请输入电话"]);
        }
        $pic = I("post.pic", "", "");
        $res = FactoryModel::ajaxImgUploadThumb($pic, "tip", 400);
        if ($res['code'] == 1) {
            $data['pic'] = $res['msg'];
        }
        $data['type'] = 2;
        M("tip")->add($data);
        $this->ajaxReturn(["msg" => "已成功"]);
    }
    //---民意直通车结束---

    //--大花园开始--
    public function gardenIndex()
    {
        $wx = WeixinService::getWxuser($this->wxTestToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $this->assign("appId", $wx['appid']);
        $this->assign("nonceStr", $wxJSApi['noncestr']);
        $this->assign("timestamp", $wxJSApi['timestamp']);
        $this->assign("wxsha1", $wxJSApi['sha1']);

        $cond['id'] = 2;
        $val = M("data_important")->where($cond)->getField("rensheng_like");
        $this->assign("cur_num", $val);
        return $this->display("Applications/garden/index");
    }

    public function gardenAdd()
    {
        $cond['id'] = 2;
        M("data_important")->where($cond)->setInc('rensheng_like');
        $data['count'] = M("data_important")->where($cond)->getField("rensheng_like");
        $this->ajaxReturn($data);
    }
    //--大花园结束--

    //---端午节变脸开始--
    public function dwfaceindex()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        $wx = WeixinService::getWxuser($this->wxZLWDToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        if (!empty($wxJSApi)) {
            $this->assign("appId", $wx['appid']);
            $this->assign("nonceStr", $wxJSApi['noncestr']);
            $this->assign("timestamp", $wxJSApi['timestamp']);
            $this->assign("wxsha1", $wxJSApi['sha1']);
        }
        return $this->display('Applications/facego/dwindex');
    }

    public function dwfacecheck()
    {
        $result = array('code' => -1, 'msg' => '图片无法识别');
        $img = I("post.img", '', '');
        if (empty($img)) {
            $result['msg'] = '无图片数据';
            $this->ajaxReturn($result);
        }
        list($type, $data) = explode(',', $img);
        $ext = '';
        if (strstr($type, 'image/jpeg') != '') {
            $ext = '.jpeg';
        } elseif (strstr($type, 'image/png') != '') {
            $ext = '.png';
        } elseif (strstr($type, 'image/jpg') != '') {
            $ext = '.jpg';
        } elseif (strstr($type, 'image/jgp') != '') {
            $ext = '.jpeg';
        }
        if (empty($ext)) {
            $result['msg'] = $type;
            $this->ajaxReturn($result);
        }
        Vendor("baidufacesdk.AipFace");
        $option = array(
            'max_face_num' => 1,
            'face_fields' => 'age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities'
        );
        $img = base64_decode($data);
        $face_result = '';
        for ($i = 0; $i < 3; $i++) {
            $rand = rand(0, 9);
            $baidu_face_array = array(
                array('app_id' => '10050796', 'api_secret' => 'uKZlRDMvgtyuVuvUeYDN7D2d', 'secret_key' => 'GYzzccZkh9aLsGm8rTnG1Gx8oTuoAQQB'),
                array('app_id' => '10050805', 'api_secret' => 'LGTGH6ikeMMFrrnQDxOcoUGw', 'secret_key' => 'lVzwtgluGVtLz2WlxmMS3WIMjEzuirYx'),
                array('app_id' => '10050811', 'api_secret' => 'wwxWZCExGWqPOz5TymXmtKOO', 'secret_key' => 'zfv2GBnrK0yNu1v9sfHHXzoahpurtwBY'),
                array('app_id' => '10050814', 'api_secret' => '8F2Fe6SmMtAhnw9fLrtowU1g', 'secret_key' => 'w189rZXMFmwSSQwybDy8ojGdY4AHjBHA'),
                array('app_id' => '10050821', 'api_secret' => 'DSE9vaY6XGIVZtXPQmylRME3', 'secret_key' => 'HOb4UqjfjHIx0RTKlTPZHWPNXvjvIphY'),
                array('app_id' => '10050825', 'api_secret' => 'sWlO5tQYT7yvHebCIcuOBLmd', 'secret_key' => 'dIeGdoaq4L9H5L0a3wx2vKElaXXsAV3i'),
                array('app_id' => '10050830', 'api_secret' => 'Pbdf6o369vib2jQHsGV3A3jL', 'secret_key' => 'k2qVqortKq0mor0GEaiNcbxKhwjqYgEh'),
                array('app_id' => '10050845', 'api_secret' => 'ogXtrdG7WGyFIWQ9owAOgAyj', 'secret_key' => 'FYkuZWPC2VhWMA0nqzTxNBqr6jSMMr3a'),
                array('app_id' => '10050849', 'api_secret' => 'FcE3GjYqLjpw2I5Exm2abYN1', 'secret_key' => 'Xbaw1KuZnyszPXGDoT4gE7pUHdoBG49F'),
                array('app_id' => '10050857', 'api_secret' => 'jbQwk8EiLa0GAHDaSd94mvaH', 'secret_key' => 'OkYS6HPqfLfjXfnwv63ff6IYRTI1cfT2')
            );;
            $baidu_face_info = $baidu_face_array[$rand];
            $apiFace = new \AipFace($baidu_face_info['app_id'], $baidu_face_info['api_secret'], $baidu_face_info['secret_key']);

            $face_result = @$apiFace->detect($img, $option);
            //--百度识别报错--
            if (isset($face_result['error_code']) || empty($face_result)) {
                continue;
            } else {
                break;
            }
        }
        if (isset($face_result['error_code']) || empty($face_result)) {
            $result['msg'] = isset($face_result['error_code']) ? $face_result['error_msg'] : "百度接口失败";
            $this->ajaxReturn($result);
        }
        //--未检测到人脸--
        if (!empty($face_result) && !empty($face_result['result_num'])) {
            if (($face_result['result']['0']['rotation_angle']) >= 10 || ($face_result['result']['0']['rotation_angle']) <= -10) {
                $result['msg'] = "人脸倾斜度过大";
                $this->ajaxReturn($result);
            } else {
                session('gender', $face_result['result']['0']['gender']);
                $result['code'] = 1;
                $result['msg'] = '成功';
                $source = imagecreatefromstring($img);
                $image = '';
                if ($face_result['result']['0']['gender'] == 'male') {
                    $image = imagerotate($source, $face_result['result']['0']['rotation_angle'] - 1, 0);
                } else {
                    $image = imagerotate($source, $face_result['result']['0']['rotation_angle'] - 2.5, 0);
                }
                $dir = "Public/Uploads/face/" . date('Ymd');
                if (!is_dir($dir)) mkdir($dir); // 如果不存在则创建
                $save_path = $dir;
                do {
                    $name = time() . rand(1, 1000000);
                    $save_path = $dir . "/" . $name . ".jpg";
                } while (file_exists($save_path));
                session('face_file', $save_path);
                imagejpeg($image, $save_path);
                imagedestroy($source);
                $this->ajaxReturn($result);
            }
        } else {
            $this->ajaxReturn($result);
        }
    }

    public function dwfacego()
    {
//        $rand = rand(0, 1000000);
        $rand = 4;
        $img_array = array(
            array(
                'imge_url' => '/Public/projects/facego/face25.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face8background.jpg?v=' . $rand,
                'face_left' => 243.7,
                'face_top' => 81,
                'face_width' => 54,
                'face_height' => 48,
                'rotate' => 20
            ),
            array(
                'imge_url' => '/Public/projects/facego/face28.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face8background.jpg?v=' . $rand,
                'face_left' => 228.3,
                'face_top' => 102,
                'face_width' => 46,
                'face_height' => 40,
                'rotate' => 20
            ),
            array(
                'imge_url' => '/Public/projects/facego/face26.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face8background.jpg?v=' . $rand,
                'face_left' => 194,
                'face_top' => 77,
                'face_width' => 41,
                'face_height' => 36,
                'rotate' => 20
            ),
            array(
                'imge_url' => '/Public/projects/facego/face27.png?v=' . $rand,
                'img_bg' => '/Public/projects/facego/face8background.jpg?v=' . $rand,
                'face_left' => 185,
                'face_top' => 96.8,
                'face_width' => 58,
                'face_height' => 57,
                'rotate' => 20
            )
        );
        $gender = session('gender');
        $rand1 = 0;
        if ($gender == 'male') {
            $rand1 = rand(0, 1);
        } else {
            $rand1 = rand(2, 3);
            $rand1 = 2;
        }
        $img_data = $img_array[$rand1];
        $this->assign('img_data', $img_data);

        $path = session('face_file');
        $this->assign('face', '/' . $path);
        Vendor("baidufacesdk.AipFace");
        $option = array(
            'max_face_num' => 1,
            'face_fields' => 'age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities'
        );
        $face_result = '';
        for ($i = 0; $i < 3; $i++) {
            $rand = rand(0, 9);
            $baidu_face_array = array(
                array('app_id' => '10050796', 'api_secret' => 'uKZlRDMvgtyuVuvUeYDN7D2d', 'secret_key' => 'GYzzccZkh9aLsGm8rTnG1Gx8oTuoAQQB'),
                array('app_id' => '10050805', 'api_secret' => 'LGTGH6ikeMMFrrnQDxOcoUGw', 'secret_key' => 'lVzwtgluGVtLz2WlxmMS3WIMjEzuirYx'),
                array('app_id' => '10050811', 'api_secret' => 'wwxWZCExGWqPOz5TymXmtKOO', 'secret_key' => 'zfv2GBnrK0yNu1v9sfHHXzoahpurtwBY'),
                array('app_id' => '10050814', 'api_secret' => '8F2Fe6SmMtAhnw9fLrtowU1g', 'secret_key' => 'w189rZXMFmwSSQwybDy8ojGdY4AHjBHA'),
                array('app_id' => '10050821', 'api_secret' => 'DSE9vaY6XGIVZtXPQmylRME3', 'secret_key' => 'HOb4UqjfjHIx0RTKlTPZHWPNXvjvIphY'),
                array('app_id' => '10050825', 'api_secret' => 'sWlO5tQYT7yvHebCIcuOBLmd', 'secret_key' => 'dIeGdoaq4L9H5L0a3wx2vKElaXXsAV3i'),
                array('app_id' => '10050830', 'api_secret' => 'Pbdf6o369vib2jQHsGV3A3jL', 'secret_key' => 'k2qVqortKq0mor0GEaiNcbxKhwjqYgEh'),
                array('app_id' => '10050845', 'api_secret' => 'ogXtrdG7WGyFIWQ9owAOgAyj', 'secret_key' => 'FYkuZWPC2VhWMA0nqzTxNBqr6jSMMr3a'),
                array('app_id' => '10050849', 'api_secret' => 'FcE3GjYqLjpw2I5Exm2abYN1', 'secret_key' => 'Xbaw1KuZnyszPXGDoT4gE7pUHdoBG49F'),
                array('app_id' => '10050857', 'api_secret' => 'jbQwk8EiLa0GAHDaSd94mvaH', 'secret_key' => 'OkYS6HPqfLfjXfnwv63ff6IYRTI1cfT2')
            );;
            $baidu_face_info = $baidu_face_array[$rand];
            $apiFace = new \AipFace($baidu_face_info['app_id'], $baidu_face_info['api_secret'], $baidu_face_info['secret_key']);

            $face_result = @$apiFace->detect(file_get_contents($path), $option);
            //--百度识别报错--
            if (isset($face_result['error_code']) || empty($face_result)) {
                continue;
            } else {
                break;
            }
        }
        if (isset($face_result['error_code']) || empty($face_result)) {
            $this->assign('code', -2);
            return $this->display('Applications/Facego/dwtest1');
        }
        //--未检测到人脸--
        if (!empty($face_result) && !empty($face_result['result_num'])) {
            $this->assign('code', 1);
            $this->assign('rotate', -($face_result['result'][0]['rotation_angle'] + $img_data['rotate']));
            $this->assign('landmark', $face_result['result'][0]['landmark72']);
            return $this->display('Applications/facego/dwtest1');
        } else {
            $this->assign('code', -4);
            return $this->display('Applications/facego/dwtest1');
        }
    }
    //---端午节变脸结束---

    //-----------------------------------温暖者端午粽子H5开始----------------------------------------------
    /*
     * 101参数缺少，102openid丢失，103没有合成粽子机会了，104没有集齐5个粽子，201服务器异常
     */
    public function wnz()
    {
        $uid = I("get.uid", -1);
        $to = I("get.to", "");
        $code = I("get.code", "");
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        if (!empty($openid)) {
            $self_uid = $this->_registerWnz();
            if ($uid != -1 && $uid == $self_uid && $to == "gift") {//自己打开
                redirect("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/wnz");
            }
            if ($uid != -1 && $uid != $self_uid && $to == "gift") {//别人打开
                $this->_helpWnzAward($uid);
                $where["id"] = $uid;
                $where["token"] = $this->wxGRZSToken;
                $where["pid"] = $this->_wennuanzhe;
                $where["status"] = RedPacketModel::STATUS_ACTIVE;
                $sharer = M("redpacket_fans")->where($where)->find();
                $lack = $this->_lackWnz($sharer["openid"]);
                $award = $this->_sendAward($sharer["openid"]);
                $this->assign("award", $award);
                $this->assign("lack", $lack);
                $this->assign("nickname", json_decode($sharer["reserve"]));
            }
            $wxJSApi = WeixinService::buildWXJSApi($this->wxTestUser);
            $wxConfig = array(
                'appId' => $this->wxTestUser['appid'],
                'timestamp' => $wxJSApi['timestamp'],
                'nonceStr' => $wxJSApi['noncestr'],
                'signature' => $wxJSApi['sha1']
            );
            $shareData = array(
                'share_title' => "温暖者的端午节",
                'share_desc' => "活着是为了温暖别人 Live. just warm others",
                'share_image' => C("SITE_URL") . "/Public/images/share_wnz.png",
                'share_link' => C("SITE_URL") . "/Wap/Applications/wnz"
            );
            StatisticsModel::visit("wnz", 1);
            $this->assign("wxConfig", $wxConfig);
            $this->assign("shareData", $shareData);
            $this->assign("uid", $self_uid);
            $this->display("Applications/wnz/index");
        } else {
            if ($code) {
                $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
                $out = $wechat->snsapiUserInfo($this->wxTestUser['appid'], $this->wxTestUser['appsecret'], $code);
                if ($out != null) {
                    session('wennuanzhe_openid_' . $this->_wennuanzhe, $out['openid']);
                    session('wennuanzhe_nickname_' . $this->_wennuanzhe, $out['nickname']);
                }
                $self_uid = $this->_registerWnz();
                if ($uid != -1 && $uid == $self_uid && $to == "gift") {//自己打开
                    redirect("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/wnz");
                }
                if ($uid != -1 && $uid != $self_uid && $to == "gift") {//别人打开
                    $this->_helpWnzAward($uid);
                    $where["id"] = $uid;
                    $where["token"] = $this->wxGRZSToken;
                    $where["pid"] = $this->_wennuanzhe;
                    $where["status"] = RedPacketModel::STATUS_ACTIVE;
                    $sharer = M("redpacket_fans")->where($where)->find();
                    $lack = $this->_lackWnz($sharer["openid"]);
                    $award = $this->_sendAward($sharer["openid"]);
                    $this->assign("award", $award);
                    $this->assign("lack", $lack);
                    $this->assign("nickname", json_decode($sharer["reserve"]));
                }
                $wxJSApi = WeixinService::buildWXJSApi($this->wxTestUser);
                $wxConfig = array(
                    'appId' => $this->wxTestUser['appid'],
                    'timestamp' => $wxJSApi['timestamp'],
                    'nonceStr' => $wxJSApi['noncestr'],
                    'signature' => $wxJSApi['sha1']
                );
                $shareData = array(
                    'share_title' => "温暖者的端午节",
                    'share_desc' => "活着是为了温暖别人 Live. just warm others",
                    'share_image' => C("SITE_URL") . "/Public/images/share_wnz.png",
                    'share_link' => C("SITE_URL") . "/Wap/Applications/wnz"
                );
                StatisticsModel::visit("wnz", 1);
                $this->assign("wxConfig", $wxConfig);
                $this->assign("shareData", $shareData);
                $this->assign("uid", $self_uid);
                $this->display("Applications/wnz/index");
            } else {
                $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
                $forward = 'http://' . $_SERVER['HTTP_HOST'] . '/Wap/Applications/wnz?' . $_SERVER['QUERY_STRING'];
                $url = $wechat->snsapiUserInfoLink($forward, $this->wxTestUser['appid']);
                redirect($url);
            }
        }
    }

    //送出的粽子
    private function _sendAward($sharer_openid)
    {
        $award = 0;
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        $where_send["token"] = $this->wxGRZSToken;
        $where_send["pid"] = $this->_wennuanzhe;
        $where_send["openid"] = $sharer_openid;
        $where_send["zhongjiang"] = 1;//1表示别人
        $where_send["status"] = RedPacketModel::STATUS_ACTIVE;
        $where_send["reserve"] = $openid;
        $send_award = M("redpacket_fansaward")->where($where_send)->find();
        if (!empty($send_award)) {
            $award = abs($send_award["award_id"]);
        }
        return $award;
    }

    //求粽子微信分享
    public function getWnzShare()
    {
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        if (!$openid) {
            $this->ajaxReturn(array('code' => 102, 'msg' => 'openid missing'));
        }
        $self_uid = $this->_registerWnz();
        $shareData = array(
            'share_title' => "温暖者的端午节，你能送我一个粽子吗？",
            'share_desc' => "活着是为了温暖别人 Live. just warm others",
            'share_image' => C("SITE_URL") . "/Public/images/share_wnz.png",
            'share_link' => C("SITE_URL") . "/Wap/Applications/wnz?to=gift&uid=" . $self_uid
        );
        $this->ajaxReturn(array('code' => 0, 'shareData' => $shareData));
    }

    //自动注册用户信息
    private function _registerWnz()
    {
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        $nickname = session("wennuanzhe_nickname_" . $this->_wennuanzhe);
        $where["token"] = $this->wxGRZSToken;
        $where["pid"] = $this->_wennuanzhe;
        $where["openid"] = $openid;
        $where["status"] = RedPacketModel::STATUS_ACTIVE;
        $fans = M("redpacket_fans")->where($where)->find();
        $uid = 0;
        if (!empty($fans)) {
            $uid = $fans["id"];
        } else {
            $data = array(
                "token" => $this->wxGRZSToken,
                "pid" => $this->_wennuanzhe,
                "openid" => $openid,
                "status" => RedPacketModel::STATUS_ACTIVE,
                "reserve" => json_encode($nickname)
            );
            $uid = M("redpacket_fans")->add($data);
        }
        return $uid;
    }

    //二维码
    public function wnzQrcode()
    {
        $uid = I("get.uid", -1);
        if ($uid == -1) {
            return "";
        }
        Vendor("phpqrcode.phpqrcode");
        $QRcode = new \QRcode();
        $url = "http://" . $_SERVER['HTTP_HOST'] . "/Wap/Applications/wnz?to=gift&uid=" . $uid;
        $level = 'L';
        $size = 4;
        $QRcode::png($url, false, $level, $size, 1);
    }

    //自己合成粽子机会，暂时没用
    public function myWnzChance()
    {
        $chance = 1;//最多只能合成1次
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        if (!$openid) {
            $this->ajaxReturn(array('code' => 102, 'msg' => 'openid missing'));
        }
        //每人合成次数
        $where["token"] = $this->wxGRZSToken;
        $where["pid"] = $this->_wennuanzhe;
        $where["openid"] = $openid;
        $where["zhongjiang"] = 0;//0表示自己，1表示别人
        $where["status"] = RedPacketModel::STATUS_ACTIVE;
        $count = M('redpacket_fansaward')->where($where)->count();
        if ($count >= $chance) {
            $chance = 0;
        }
        $this->ajaxReturn(array('code' => 0, 'chance' => $chance));
    }

    //别人帮助随机生成
    private function _helpWnzAward($uid)
    {
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);//帮助的人
        $where["id"] = $uid;
        $where["token"] = $this->wxGRZSToken;
        $where["pid"] = $this->_wennuanzhe;
        $where["status"] = RedPacketModel::STATUS_ACTIVE;
        $sharer = M("redpacket_fans")->where($where)->find();//求粽子的人
        if (empty($sharer)) {
            return false;
        }
        $prize_num = 500;                   //总奖品数是500
        $pr = array(-1 => 25, -2 => 25, -3 => 25, -5 => 25);//不包含特殊粽子
        $pr_special = array(-4 => 5, -1 => 25, -2 => 25, -3 => 25, -5 => 25);//包括特殊粽子
        $redpacket_fansaward = M("redpacket_fansaward");
        //别人帮助合成粽子次数
        $where_fans["token"] = $this->wxGRZSToken;
        $where_fans["pid"] = $this->_wennuanzhe;
        $where_fans["openid"] = $sharer["openid"];
        $where_fans["zhongjiang"] = 1;//1表示别人
        $where_fans["status"] = RedPacketModel::STATUS_ACTIVE;
        $where_fans["reserve"] = $openid;
        $count = $redpacket_fansaward->where($where_fans)->count();
        if ($count >= 1) {
            return false;
        }
        //自己获得粽子4的总量，不得超过1
        $where_count["token"] = $this->wxGRZSToken;
        $where_count["pid"] = $this->_wennuanzhe;
        $where_count["openid"] = $sharer["openid"];
        $where_count["award_id"] = -4;
        $where_count["status"] = RedPacketModel::STATUS_ACTIVE;
        $count = $redpacket_fansaward->where($where_count)->count();
        //获得粽子4的总量，不得超过总奖品数
        $where_prize["token"] = $this->wxGRZSToken;
        $where_prize["pid"] = $this->_wennuanzhe;
        $where_prize["award_id"] = -4;
        $where_prize["status"] = RedPacketModel::STATUS_ACTIVE;
        $prize_count = $redpacket_fansaward->where($where_prize)->count();
        if ($count >= 1 || $prize_count >= $prize_num) {
            //普通粽子
            $this->_wnzLogic($pr, $sharer["openid"]);
        } else {
            //普通粽子+特殊粽子
            $this->_wnzLogic($pr_special, $sharer["openid"]);
        }
    }

    //自己随机生成1个粽子
    public function generateWnzAward()
    {
        $prize_num = 500;                   //总奖品数是500
        $pr = array(-1 => 25, -2 => 25, -3 => 25, -5 => 25);//不包含特殊粽子
        $pr_special = array(-4 => 5, -1 => 25, -2 => 25, -3 => 25, -5 => 25);//包括特殊粽子
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        if (!$openid) {
            $this->ajaxReturn(array('code' => 102, 'msg' => 'openid missing'));
        }
        $redpacket_fansaward = M("redpacket_fansaward");
        //自己合成粽子次数
        $where_fans["token"] = $this->wxGRZSToken;
        $where_fans["pid"] = $this->_wennuanzhe;
        $where_fans["openid"] = $openid;
        $where_fans["zhongjiang"] = 0;//0表示自己
        $where_fans["status"] = RedPacketModel::STATUS_ACTIVE;
        $count = $redpacket_fansaward->where($where_fans)->count();
        if ($count >= 1) {
            $this->ajaxReturn(array('code' => 103, 'msg' => 'no chance'));
        }
        //自己获得粽子4的总量，不得超过1
        $where_count["token"] = $this->wxGRZSToken;
        $where_count["pid"] = $this->_wennuanzhe;
        $where_count["openid"] = $openid;
        $where_count["award_id"] = -4;
        $where_count["status"] = RedPacketModel::STATUS_ACTIVE;
        $award_count = $redpacket_fansaward->where($where_count)->count();
        //获得粽子4的总量，不得超过总奖品数
        $where_prize["token"] = $this->wxGRZSToken;
        $where_prize["pid"] = $this->_wennuanzhe;
        $where_prize["award_id"] = -4;
        $where_prize["status"] = RedPacketModel::STATUS_ACTIVE;
        $prize_count = $redpacket_fansaward->where($where_prize)->count();
        if ($award_count >= 1 || $prize_count >= $prize_num) {
            //普通粽子
            $this->_wnzLogic($pr);
        } else {
            //普通粽子+特殊粽子
            $this->_wnzLogic($pr_special);
        }
    }

    //中奖逻辑
    private function _wnzLogic($pr, $sharer_openid = "")
    {
        $result = '';
        $proSum = array_sum($pr);
        foreach ($pr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        if (!empty($sharer_openid)) {
            $this->_helpSaveWnzAward($result, $sharer_openid, $pr);
        } else {
            $this->_saveWnzAward($result, $pr);
        }
    }

    //普通粽子
    private function _normalAward($sharer_openid = '')
    {
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        $pr = array(-1 => 25, -2 => 25, -3 => 25, -5 => 25);//不包含特殊粽子
        $rand = array_rand($pr);
        if (!empty($sharer_openid)) {
            $data = array(
                "token" => $this->wxGRZSToken,
                "pid" => $this->_wennuanzhe,
                "openid" => $sharer_openid,
                "award_id" => $rand,
                "zhongjiang" => 1,//1表示帮助
                "status" => RedPacketModel::STATUS_ACTIVE,
                "reserve" => $openid
            );
        } else {
            $data = array(
                "token" => $this->wxGRZSToken,
                "pid" => $this->_wennuanzhe,
                "openid" => $openid,
                "award_id" => $rand,
                "zhongjiang" => 0,//0表示自己
                "status" => RedPacketModel::STATUS_ACTIVE
            );
        }
        M("redpacket_fansaward")->add($data);
    }

    //别人帮助，保存中奖信息，数据库使用地址访问，使用事件回滚，award_id中奖id
    private function _helpSaveWnzAward($award_id, $sharer_openid = "", $pr)
    {
        $prize_num = 500;                   //总奖品数是500
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        $redpacket_fansaward = M("redpacket_fansaward");
        $redpacket_fansaward->startTrans();
        $data = array(
            "token" => $this->wxGRZSToken,
            "pid" => $this->_wennuanzhe,
            "openid" => $sharer_openid,
            "award_id" => $award_id,
            "zhongjiang" => 1,//1表示帮助
            "status" => RedPacketModel::STATUS_ACTIVE,
            "reserve" => $openid
        );
        $redpacket_fansaward->add($data);
        //别人最多帮助合成1次
        $where_fans["token"] = $this->wxGRZSToken;
        $where_fans["pid"] = $this->_wennuanzhe;
        $where_fans["openid"] = $sharer_openid;
        $where_fans["zhongjiang"] = 1;//1表示别人帮助
        $where_fans["status"] = RedPacketModel::STATUS_ACTIVE;
        $where_fans["reserve"] = $openid;
        if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
            $count = M("redpacket_fansaward", 'esm_',
                'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                ->where($where_fans)->count();
        } else {
            $count = $redpacket_fansaward->where($where_fans)->count();
        }
        if ($count > 1) {
            $redpacket_fansaward->rollback();
            return false;
        }
        //他人获得粽子4的总量，不得超过1
        $where_prize["token"] = $this->wxGRZSToken;
        $where_prize["pid"] = $this->_wennuanzhe;
        $where_prize["openid"] = $sharer_openid;
        $where_prize["award_id"] = -4;
        $where_prize["status"] = RedPacketModel::STATUS_ACTIVE;
        if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
            $prize_count = M("redpacket_fansaward", 'esm_',
                'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                ->where($where_prize)->count();
        } else {
            $prize_count = $redpacket_fansaward->where($where_prize)->count();
        }
        if ($prize_count > 1) {
            $redpacket_fansaward->rollback();
            $this->_normalAward($sharer_openid);
            return false;
        }
        //所有获得粽子4的总量，不得超过总奖品数
        $where_all["token"] = $this->wxGRZSToken;
        $where_all["pid"] = $this->_wennuanzhe;
        $where_all["award_id"] = -4;
        $where_all["status"] = RedPacketModel::STATUS_ACTIVE;
        if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
            $award_count = M("redpacket_fansaward", 'esm_',
                'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                ->where($where_all)->count();
        } else {
            $award_count = $redpacket_fansaward->where($where_all)->count();
        }
        if ($award_count > $prize_num) {
            $redpacket_fansaward->rollback();
            $this->_normalAward($sharer_openid);
            return false;
        }
        $redpacket_fansaward->commit();
    }

    //自己抽奖，保存中奖信息，数据库使用地址访问，使用事件回滚，award_id中奖id
    private function _saveWnzAward($award_id, $pr)
    {
        $prize_num = 500;                   //总奖品数是500
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        $redpacket_fansaward = M("redpacket_fansaward");
        $redpacket_fansaward->startTrans();
        $data = array(
            "token" => $this->wxGRZSToken,
            "pid" => $this->_wennuanzhe,
            "openid" => $openid,
            "award_id" => $award_id,
            "zhongjiang" => 0,//0表示自己
            "status" => RedPacketModel::STATUS_ACTIVE
        );
        $redpacket_fansaward->add($data);
        //自己最多合成次数
        $where_fans["token"] = $this->wxGRZSToken;
        $where_fans["pid"] = $this->_wennuanzhe;
        $where_fans["openid"] = $openid;
        $where_fans["zhongjiang"] = 0;//0表示自己
        $where_fans["status"] = RedPacketModel::STATUS_ACTIVE;
        if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
            $count = M("redpacket_fansaward", 'esm_',
                'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                ->where($where_fans)->count();
        } else {
            $count = $redpacket_fansaward->where($where_fans)->count();
        }
        if ($count > 1) {
            $redpacket_fansaward->rollback();
            $this->ajaxReturn(array('code' => 103, 'msg' => 'no chance'));
        }
        //自己获得粽子4的总量，不得超过1
        $where_prize["token"] = $this->wxGRZSToken;
        $where_prize["pid"] = $this->_wennuanzhe;
        $where_prize["openid"] = $openid;
        $where_prize["award_id"] = -4;
        $where_prize["status"] = RedPacketModel::STATUS_ACTIVE;
        if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
            $prize_count = M("redpacket_fansaward", 'esm_',
                'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                ->where($where_prize)->count();
        } else {
            $prize_count = $redpacket_fansaward->where($where_prize)->count();
        }
        if ($prize_count > 1) {
            $redpacket_fansaward->rollback();
            $this->ajaxReturn(array('code' => 103, 'msg' => 'no chance'));
        }
        //所有人获得粽子4的总量，不得超过总奖品数
        $where_all["token"] = $this->wxGRZSToken;
        $where_all["pid"] = $this->_wennuanzhe;
        $where_all["award_id"] = -4;
        $where_all["status"] = RedPacketModel::STATUS_ACTIVE;
        if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
            $award_count = M("redpacket_fansaward", 'esm_',
                'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                ->where($where_all)->count();
        } else {
            $award_count = $redpacket_fansaward->where($where_all)->count();
        }
        if ($award_count > $prize_num) {
            $redpacket_fansaward->rollback();
            $this->_normalAward();
            return false;
        } else {
            $redpacket_fansaward->commit();
            $lack = $this->_lackWnz($openid);
            $this->ajaxReturn(array('code' => 0, 'award' => abs($award_id), 'lack' => $lack));
        }
    }

    //还差几种粽子集齐
    private function _lackWnz($openid)
    {
        $lack = 5;
        $where['token'] = $this->wxGRZSToken;
        $where['pid'] = $this->_wennuanzhe;
        $where['openid'] = $openid;
        $where['award_id'] = array("in", array(-1, -2, -3, -4, -5));
        $where['status'] = RedPacketModel::STATUS_ACTIVE;
        $list = M("redpacket_fansaward")->where($where)->field("award_id")->select();
        if (!empty($list)) {
            foreach ($list as $value) {
                $award[] = $value["award_id"];
            }
            $award = array_flip(array_flip($award));
            $lack = $lack - count($award);
        }
        return $lack;
    }

    //我的粽子，奖品award_id：-1、-2、-3、-4、-5，-4特殊粽子
    public function myWnzAwards()
    {
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        if (!$openid) {
            $this->ajaxReturn(array('code' => 102, 'msg' => 'openid missing'));
        }
        $where['token'] = $this->wxGRZSToken;
        $where['pid'] = $this->_wennuanzhe;
        $where['openid'] = $openid;
        $where['award_id'] = array("in", array(-1, -2, -3, -4, -5));
        $where['status'] = RedPacketModel::STATUS_ACTIVE;
        $fansaward = M("redpacket_fansaward")->where($where)->order('createdate desc')->select();
        $award1 = $award2 = $award3 = $award4 = $award5 = $showForm = 0;
        if (!empty($fansaward)) {
            foreach ($fansaward as $value) {
                switch ($value["award_id"]) {
                    case -1:
                        $award1++;
                        break;
                    case -2:
                        $award2++;
                        break;
                    case -3:
                        $award3++;
                        break;
                    case -4:
                        $award4++;
                        break;
                    case -5:
                        $award5++;
                        break;
                    default:
                        break;
                }
            }
        }
        if ($award1 >= 1 && $award2 >= 1 && $award3 >= 1 && $award4 >= 1 && $award5 >= 1) {
            $showForm = 1;
        }
        $where_fans["token"] = $this->wxGRZSToken;
        $where_fans["pid"] = $this->_wennuanzhe;
        $where_fans["openid"] = $openid;
        $where_fans["status"] = RedPacketModel::STATUS_ACTIVE;
        $fans = M("redpacket_fans")->where($where_fans)->find();
        if ($showForm == 1 && !empty($fans["name"]) && !empty($fans["phone"])) {
            $showForm = 2;
        }
        $this->ajaxReturn(array("code" => 0, "award1" => $award1, "award2" => $award2, "award3" => $award3,
            "award4" => $award4, "award5" => $award5, "showForm" => $showForm));
    }

    //用户填写信息
    public function registerWnzInfo()
    {
        $name = I("post.name", "");
        $phone = I("post.phone", "");
        if ($name == "" || $phone == "") {
            $this->ajaxReturn(array('code' => 101, 'msg' => 'required parameter missing'));
        }
        $openid = session("wennuanzhe_openid_" . $this->_wennuanzhe);
        if (!$openid) {
            $this->ajaxReturn(array('code' => 102, 'msg' => 'openid missing'));
        }
        $lack = $this->_lackWnz($openid);
        if ($lack > 0) {
            $this->ajaxReturn(array('code' => 104, 'msg' => 'not collect all yet'));
        }
        $where_fans['id'] = $this->_registerWnz();
        $data = array('name' => $name, 'phone' => $phone);
        $updated = M('redpacket_fans')->where($where_fans)->save($data);
        if ($updated !== false) {
            $this->ajaxReturn(array('code' => 0));
        } else {
            $this->ajaxReturn(array('code' => 201, 'msg' => 'server error'));
        }
    }

    //导出粽子名单
    public function downloadWnz()
    {
//        $where['esm_redpacket_fans.token'] = $this->wxGRZSToken;
//        $where['esm_redpacket_fans.pid'] = $this->_wennuanzhe;
//        $where['esm_redpacket_fans.status'] = RedPacketModel::STATUS_ACTIVE;
//        $where['award.token'] = $this->wxGRZSToken;
//        $where['award.pid'] = $this->_wennuanzhe;
//        $where['award.award_id'] = -4;//特殊粽子
//        $where['award.status'] = RedPacketModel::STATUS_ACTIVE;
//        $list = M("redpacket_fans")
//            ->join("LEFT JOIN esm_redpacket_fansaward as award ON award.openid = esm_redpacket_fans.openid")
//            ->where($where)->order('esm_redpacket_fans.createdate desc')
//            ->field("award.createdate,esm_redpacket_fans.name,esm_redpacket_fans.phone,esm_redpacket_fans.reserve")
//            ->select();
        $suc = I("get.success", 0);
        $where["token"] = $this->wxGRZSToken;
        $where["pid"] = $this->_wennuanzhe;
        $where["award_id"] = -4;//特殊粽子
        $where["status"] = RedPacketModel::STATUS_ACTIVE;
        $awards = M("redpacket_fansaward")->where($where)->field("openid")->select();
        if (!empty($awards)) {
            foreach ($awards as $award) {
                $fans[] = $award["openid"];
            }
            $fans = array_flip(array_flip($fans));
            $where_fans["token"] = $this->wxGRZSToken;
            $where_fans["pid"] = $this->_wennuanzhe;
            $where_fans["openid"] = array("in", $fans);
            $where_fans["status"] = RedPacketModel::STATUS_ACTIVE;
            if ($suc == 1) {
                $where_fans["name"] = array("exp", "is not null");
                $where_fans["phone"] = array("exp", "is not null");
            }
            $list = M("redpacket_fans")->where($where_fans)->order("id desc")->select();
        }
        if (!empty($list)) {
            set_time_limit(0);
            vendor('phpexcel.PHPExcel');
            $objExcel = new \PHPExcel();
            $objActSheet = $objExcel->getActiveSheet();
            $objActSheet->getColumnDimension('A')->setWidth(30);
            $objActSheet->getColumnDimension('B')->setWidth(50);
            $objActSheet->getColumnDimension('C')->setWidth(50);
            $objActSheet->getColumnDimension('D')->setWidth(50);
            $objActSheet->setCellValue('A1', "姓名");
            $objActSheet->setCellValue('B1', "联系电话");
            $objActSheet->setCellValue('C1', "集齐时间");
            $objActSheet->setCellValue('D1', "微信昵称");
            $line = 2;
            foreach ($list as $value) {
                $objActSheet->setCellValue('A' . $line, $value['name']);
                $objActSheet->setCellValue('B' . $line, $value['phone']);
                $objActSheet->setCellValue('C' . $line, $value['createdate']);
                $objActSheet->setCellValue('D' . $line, json_decode($value['reserve']));
                $line++;
            }
            $fileName = '集齐五粽名单' . date('Ymd') . '.xlsx';
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
            $objWriter->save('php://output');
        }
    }
    //-----------------------------------温暖者端午粽子H5结束----------------------------------------------

    //-----------------------------------大花园总作品数、点赞数开始-----------------------------------------
    public function dhy()
    {
        $where["praise_id"] = 121;
        $where["token"] = "kymcln1430124680";
        $where["status"] = array('NEQ', -1);
        $count1 = M("praise_item")->where($where)->count();
        $count2 = M("praise_item")->where($where)->sum("votes");
        $date = date("m月d日 H:i");
        $this->assign("msg", "截止" . $date . "，大花园总作品数" . $count1 . "个，总点赞数" . $count2);
        $this->display("Applications/wnz/dhy");
    }
    //-----------------------------------大花园总作品数、点赞数结束-----------------------------------------

    //--人脸融合开始--
    public function rlrh_index()
    {
        $wx = WeixinService::getWxuser($this->wxZLWDToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        if (!empty($wxJSApi)) {
            $this->assign("appId", $wx['appid']);
            $this->assign("nonceStr", $wxJSApi['noncestr']);
            $this->assign("timestamp", $wxJSApi['timestamp']);
            $this->assign("wxsha1", $wxJSApi['sha1']);
        }
        $this->display("Applications/rlrh/index");
    }

    public function rlrh_check()
    {
        $male = I("post.male", 0, "");
        $SecretID = 'AKIDEZv6CDgqwtnYDht992CJIAtrjkiagm92';
        $secretKey = 'yqmbau8RgkpnzZ8IPM9zX2b0Pjy630z0';
        $orignal = 'u=513885808&a=10136787&k=AKIDEZv6CDgqwtnYDht992CJIAtrjkiagm92&e=0&t=1530676656&r=270494647&f=';
        $signStr = base64_encode(hash_hmac('sha1', $orignal, $secretKey, true) . $orignal);

        $post_data['app_id'] = '10136787';
        $post_data['rsp_img_type'] = 'url';
        $img_data = I("post.img", "", "");
        $post_data['img_data'] = $img_data;
        if ($male == 0) {
            $post_data['opdata'] = [
                ["cmd" => "doFaceMerge", "params" => ["model_id" => "youtu_75771_20180709161109_1889"]]
            ];
        } else {
            $post_data['opdata'] = [
                ["cmd" => "doFaceMerge", "params" => ["model_id" => "youtu_75771_20180709160527_1888"]]
            ];
        }

        $postdata = json_encode($post_data);
        $content_length = strlen($postdata);
        $header = [
            "Host:api.youtu.qq.com",
            "Content-Length:" . $content_length,
            "Content-Type:text/json",
            "Authorization:" . $signStr
        ];
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, "http://api.youtu.qq.com/cgi-bin/pitu_open_access_for_youtu.fcg");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // 3. 执行并获取HTML文档内容
        $output = curl_exec($ch);
        if ($output === FALSE) {
            echo "CURL Error:" . curl_error($ch);
        }
        // 4. 释放curl句柄
        curl_close($ch);
        $output = json_decode($output, true);
        if (!empty($output['img_url'])) {
            $this->ajaxReturn($output['img_url']);
        } else {
            $this->ajaxReturn(0);
        }
    }

    public function rlrh()
    {
        $img = I("get.img", "", "");
        $this->assign("img", $img);
        $this->display("Applications/rlrh/end");
    }
    //--人脸融合结束--

    //---人脸检索开始---
    public function rlidentity()
    {

    }

    //---人脸检索结束---

    //-------------------------------支付宝H5开始--------------------------------------
    public function setZero()
    {
        session('ant_userid_' . $this->wxTestToken, null);
    }

    public function ant()
    {
        //判断访问来源
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($agent, 'MicroMessenger')) {//微信
            $code = I('get.code', -1);
            $openid = session('ant_openid_' . $this->wxTestToken);
            if ($openid) {
                $config = $this->_antShare(1);
                $this->assign('wxConfig', $config['wxConfig']);
                $this->assign('wxShare', $config['wxShare']);
                $this->assign('app', 'wx');
                FactoryModel::viewPage(3);
                $this->display('Applications/ant/index');
            } else {
                if ($code != -1) {
                    $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
                    $openid = $wechat->snsapiBaseUser($code);
                    session('ant_openid_' . $this->wxTestToken, $openid);
                    $this->_registerAntUser($openid, 1);
                    $config = $this->_antShare(1);
                    $this->assign('wxConfig', $config['wxConfig']);
                    $this->assign('wxShare', $config['wxShare']);
                    $this->assign('app', 'wx');
                    FactoryModel::viewPage(3);
                    $this->display('Applications/ant/index');
                } else {
                    $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
                    $url = $wechat->buildOauthURI(C('SITE_URL') . '/Wap/Applications/ant?' . $_SERVER['QUERY_STRING']);
                    redirect($url);
                }
            }
        } elseif (strpos($agent, 'AlipayClient')) {//支付宝
            $app_id = '2018103161898551';
            $auth_code = I('get.auth_code', -1);
            $userid = session('ant_userid_' . $this->wxTestToken);
            if ($userid) {
                $config = $this->_antShare(2);
                $this->assign('aliShare', $config['aliShare']);
                $this->assign('app', 'alipay');
                FactoryModel::viewPage(3);
                $this->display('Applications/ant/index');
            } else {
                if ($auth_code != -1) {
                    vendor('Alipay.AopSdk');
                    $aop = new \AopClient();
                    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                    $aop->appId = $app_id;
                    $aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEAvrjv+4YoyAVWmGMmIqSWCWCPQ/fHysupkKLkTYk/FGm93zhUwqzIOGhahzUt/7c6KkThf/pRNe61x8FYFds86j+M8lQ4Tan467VVVcqxuASpsllaibdGqBxzpE8JjbmV1fN+59hRKjiwIaAMXWUFoYs+zYVTv6Sd9ZIebOdY13ptoyJijpBhK0RQ+0oa8M+zQUOHPoCq9TChm27KzaXK6TtH4qDluf9cjsrSRILh7KA9ABrXlDooXH7FLLGZV/z8B2ONirj3O6uJMN3NKCkuThRQAvhC3NBm/xb/7GicRAGZy3B/WmAOoIPj6DKa+aYWKjrkhVC9eaKSKLtqyqZyjQIDAQABAoIBAQCPZ0TijYyKYSEscZiSAcjigh0W0O8Dt8DmhOQ+vIyWj695cMSioAHoD+bJtR3CIYX1lFctwAxiDfvWl7TgsjkKNQCIkPTIyJ3mtTDV0hNwtujVtkPSOuFAtCvrhpY7Xyifd3ebYdYddgRRNCM38iaawbVWGQLQnTk8FUMVRZpSYWogcRijJq81jd4NBrFuBGJOp78tVXps/12oN11oNYyBFZCs8O5pAsaIbu6VtMZ8ocZ4LPVeQrb9AiTtSV/wnd/QiR9hq4HCwjLQMo0nQ/TnWsKfnWQxx2xx0w7oAouGqG1YRv9CPyelABqIQvK0ROSo+ZrJkhG/3lAwaB3dv5YNAoGBAOT+VTpq6EYPDi7mcfMnklEkvgw98DEWVXQwciKI5BItgx3e01pAETl9qeknH8rrvsDs8KhhLCAb7cnMWP+/PJysm6g0UWBUgQe05sqVuFs6hK+IEfPS9FDA/9au7Dp2t2dk/o40mIhkrgf8zl4ask6dHYuf8mAa9ZVyb7Y6/ax3AoGBANU3JECqBtzwXpLyLGb/I9+ewfPbG/yyYb5FPTQU949lyVnQAnSPl8k6Aa1suvQ1qBv1zg/IjJgwjznwX8NMR71RD6QSgUbwNKzElz3Jd4UoimqRf5OCY3XPinaIaFYjR5wUtAlm/y4k+mi/OFrR1NvGyhy8TUq5kGXqLYUur04bAoGAGrV/g1zM0r8WzGmciNvouQYsFIl05oTQWsj7xwNodqZQUL+Yr0IhwC7kDom9r5FnomEAgOM0nlojlhH7n3jSvQN09F2F0FKK6jczZBWqdxmQOFkKnwHP9UtNi+DDNN577dddyYBg+iekFNJrz5YVjg3NUGfLgWIjmtbKKNsgk2kCgYAl1H7OKlzFXrCpCebu714CEzz+c2Xn1A6bn9VYJFA4VSsAkHOfEssvnOcnSh9xrQOC0n4ZNtAbQKJo+UlEcYhZAsTvq4jceUofTVI4WEKokaTde6tTFNNo18YNee5pOiE+hD3dXTTxjwYPB76L/qbxx7ecmZxtIbeJHZ+t/baE+QKBgQDNot3ldZ2OlrVQaVlkZw0NHhVBEFAVt1tnjInChAyB7T3ts1lCDWJ9LEvZ9KPPDbjiEtF8oJM7TkHKfJQ59cazhc14geFCVY0XOZ6uEsZtZoxkfyVZMzH+93A/o0hjodU7NphcPSwbt/JM1FZdgCiJExxSLAZaIIX/S9oprP4vMg==';
                    $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApw4PbcjvZwa9sh0tIx8fnbtliIlgRtjbM/XEh/bIoSg43ylhKuLbSqIYj6hU+NouZdZo/qu2S2PAymBTO2ZCdKdjQiGY+t4JgTw0982+7o+waG/NK2/WVJbTLakv+vb0FvXPxXmwQNNPixO93T6hDfdYXwzw2eLHfVhcO8EZlWtoMWSvvwq1EVq0Pt8H/0ZNSwwjF59xmMooImsUj47TIJ5atICUJaS5hWHbT1F9Ke6GNUzvTF44kGz594BG0+GRwbzEZpFD217MKjQ4lRlBLq992e7sOuhCq2s+Etmvf8HFOkWZvQglLavqjcR2AUM1btzIHHU8GVnvSQvr8d79rQIDAQAB';
                    $aop->apiVersion = '1.0';
                    $aop->signType = 'RSA2';
                    $aop->postCharset = 'UTF-8';
                    $aop->format = 'json';
                    //获取access_token、user_id
                    $request = new \AlipaySystemOauthTokenRequest();
                    $request->setGrantType("authorization_code");
                    $request->setCode($auth_code);
                    $result = $aop->execute($request);
                    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                    $access_token = $result->$responseNode->access_token;
                    $userid = $result->$responseNode->user_id;
                    $refresh_token = $result->$responseNode->refresh_token;
                    session('ant_userid_' . $this->wxTestToken, $userid);
                    $this->_registerAntUser($userid, 2);
//                    //获取用户信息
//                    $request_a = new \AlipayUserUserinfoShareRequest();
//                    $result_a = $aop->execute ($request_a, $access_token);
//                    $responseNode_a = str_replace(".", "_", $request_a->getApiMethodName()) . "_response";
//
//                    $alipayUser = array();
//                    $alipayUser['alipay_user_id'] = $result_a->$responseNode_a->user_id;
//                    $alipayUser['avatar'] = $result_a->$responseNode_a->avatar;
//                    $alipayUser['nick_name'] = $result_a->$responseNode_a->nick_name;
//                    $this->assign('nickname', $alipayUser['nick_name']);
//                    $this->assign('avatar', $alipayUser['avatar']);
                    $config = $this->_antShare(2);
                    $this->assign('aliShare', $config['aliShare']);
                    $this->assign('app', 'alipay');
                    FactoryModel::viewPage(3);
                    $this->display('Applications/ant/index');
                } else {
                    $redirect_url = C('SITE_URL') . '/Wap/Applications/ant';
                    if (stripos($agent, 'iPhone') !== false) {
                        $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' . $app_id .
                            '&scope=auth_base&redirect_uri=' . urlencode($redirect_url);
                    } else {//部分安卓机需要授权访问,不然一直循环跳转，如huawei mate 9
                        $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' . $app_id .
                            '&scope=auth_userinfo&redirect_uri=' . urlencode($redirect_url);
                    }
                    //scope: auth_userinfo、auth_base
                    redirect($url);
                }
            }
        } else {//其它浏览器
            $config = $this->_antShare(3);//给钉钉准备
            $this->assign('wxConfig', '');
            $this->assign('wxShare', '');
            $this->assign('aliShare', $config['aliShare']);
            $this->assign('app', 'other');
            FactoryModel::viewPage(3);
            $this->display('Applications/ant/index');
        }
    }

    //注册用户信息，type：1微信，2支付宝
    private function _registerAntUser($openid_or_userid, $type)
    {
        $where['token'] = $this->wxTestToken;
        $where['pid'] = $this->_ant;
        $where['openid'] = $openid_or_userid;
        $where['status'] = 1;
        $where['sex'] = $type;
        $record = M('redpacket_fans')->where($where)->find();
        if (empty($record)) {
            $data = array(
                'token' => $this->wxTestToken,
                'pid' => $this->_ant,
                'openid' => $openid_or_userid,
                'sex' => $type
            );
            M('redpacket_fans')->add($data);
        }
    }

    //分享设置,type:1微信，2支付宝
    private function _antShare($type)
    {
        $wxConfig = array();
        $wxShare = $aliShare = array(
            'share_title' => '暖，互联网改变的100张面孔',
            'share_desc' => '线上影展',
            'share_link' => C('SITE_URL') . '/Wap/Applications/ant',
            'share_image' => C('SITE_URL') . '/Public/images/ant/share_ant.png'
        );
        if ($type == 1) {
            $wx = WeixinService::getWxuser($this->wxTestToken);
            $wxJSApi = WeixinService::buildWXJSApi($wx);
            if (!empty($wxJSApi)) {
                $wxConfig = array(
                    'appId' => $wx['appid'],
                    'nonceStr' => $wxJSApi['noncestr'],
                    'timestamp' => $wxJSApi['timestamp'],
                    'signature' => $wxJSApi['sha1']
                );
            }
        }
        $config = array(
            'wxConfig' => $wxConfig,
            'wxShare' => $wxShare,
            'aliShare' => $aliShare
        );
        return $config;
    }

    //图片列表
    public function antList()
    {
        $type = I('get.type', 1);
        $list = array();
        $file_path = './Public/json/ant.json';
        if (file_exists($file_path)) {
            $json_string = file_get_contents($file_path);
            $data = json_decode($json_string, true);
            if (!empty($data)) {
                foreach ($data as $value) {
                    if ($value['type'] == $type) {
                        $flag[] = $value['displayorder'];
                        $list[] = array(
                            'id' => $value['id'],
                            'image' => C('SITE_URL') . $value['image']
                        );
                    }
                }
                array_multisort($flag, SORT_ASC, $list);
            }
        }
        $this->ajaxReturn(array('code' => 0, 'list' => $list));
    }

    //图片详情
    public function antDetail()
    {
        $id = I('get.id', -1);
        if ($id == -1) {
            $this->ajaxReturn(array('code' => 101, 'msg' => 'required parameter missing'));
        }
        $image = $text = '';
        $file_path = './Public/json/ant.json';
        if (file_exists($file_path)) {
            $json_string = file_get_contents($file_path);
            $data = json_decode($json_string, true);
            if (isset($data[$id])) {
                $image = C('SITE_URL') . $data[$id]['image'];
                $text = $data[$id]['text'];
            } else {
                $this->ajaxReturn(array('code' => 106, 'msg' => 'invalid id'));
            }
        } else {
            $this->ajaxReturn(array('code' => 106, 'msg' => 'invalid id'));
        }
        //是否显示点赞区域
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($agent, 'MicroMessenger')) {
            $show_praise = 1;
            $openid_or_userid = session('ant_openid_' . $this->wxTestToken);
            if (!$openid_or_userid) {
                $this->ajaxReturn(array('code' => 102, 'msg' => 'openid missing'));
            }
        } elseif (strpos($agent, 'AlipayClient')) {
            $show_praise = 1;
            $openid_or_userid = session('ant_userid_' . $this->wxTestToken);
            if (!$openid_or_userid) {
                $this->ajaxReturn(array('code' => 103, 'msg' => 'userid missing'));
            }
        } else {
            $show_praise = 0;
        }
        //当前是否点赞过
        $where_self['token'] = $this->wxTestToken;
        $where_self['pid'] = $this->_ant;
        $where_self['award_id'] = $id;
        $where_self['status'] = 1;
        $where_self['openid'] = $openid_or_userid;
        if (strpos($agent, 'MicroMessenger')) {
            $where_self['zhongjiang'] = 1;//1微信，2支付宝
            $record = M('redpacket_fansaward')->where($where_self)->find();
        } elseif (strpos($agent, 'AlipayClient')) {
            $where_self['zhongjiang'] = 2;//1微信，2支付宝
            $record = M('redpacket_fansaward')->where($where_self)->find();
        } else {
            $record = array();
        }
        if (!empty($record)) {
            $has_praise = 1;
        } else {
            $has_praise = 0;
        }
        $this->ajaxReturn(array('code' => 0, 'image' => $image, 'text' => $text, 'show_praise' => $show_praise,
            'has_praise' => $has_praise));
    }

    //保存点赞
    public function antPraise()
    {
        $id = I('post.id', -1);
        if ($id == -1) {
            $this->ajaxReturn(array('code' => 101, 'msg' => 'required parameter missing'));
        }
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($agent, 'MicroMessenger')) {//微信
            $openid = session('ant_openid_' . $this->wxTestToken);
            if (!$openid) {
                $this->ajaxReturn(array('code' => 102, 'msg' => 'openid missing'));
            }
            $where['token'] = $this->wxTestToken;
            $where['pid'] = $this->_ant;
            $where['openid'] = $openid;
            $where['award_id'] = $id;
            $where['zhongjiang'] = 1;//1微信，2支付宝
            $where['status'] = 1;
            $record = M('redpacket_fansaward')->where($where)->find();
            if (!empty($record)) {
                $this->ajaxReturn(array('code' => 105, 'msg' => 'already praised'));
            } else {
                $data = array(
                    'token' => $this->wxTestToken,
                    'pid' => $this->_ant,
                    'openid' => $openid,
                    'award_id' => $id,
                    'zhongjiang' => 1
                );
                $added = M('redpacket_fansaward')->add($data);
                if ($added !== false) {
                    $this->ajaxReturn(array('code' => 0));
                } else {
                    $this->ajaxReturn(array('code' => 201, 'msg' => 'server error'));
                }
            }
        } elseif (strpos($agent, 'AlipayClient')) {//支付宝
            $userid = session('ant_userid_' . $this->wxTestToken);
            if (!$userid) {
                $this->ajaxReturn(array('code' => 103, 'msg' => 'userid missing'));
            }
            $where['token'] = $this->wxTestToken;
            $where['pid'] = $this->_ant;
            $where['openid'] = $userid;
            $where['award_id'] = $id;
            $where['zhongjiang'] = 2;//1微信，2支付宝
            $where['status'] = 1;
            $record = M('redpacket_fansaward')->where($where)->find();
            if (!empty($record)) {
                $this->ajaxReturn(array('code' => 105, 'msg' => 'already praised'));
            } else {
                $data = array(
                    'token' => $this->wxTestToken,
                    'pid' => $this->_ant,
                    'openid' => $userid,
                    'award_id' => $id,
                    'zhongjiang' => 2
                );
                $added = M('redpacket_fansaward')->add($data);
                if ($added !== false) {
                    $this->ajaxReturn(array('code' => 0));
                } else {
                    $this->ajaxReturn(array('code' => 201, 'msg' => 'server error'));
                }
            }
        } else {
            $this->ajaxReturn(array('code' => 104, 'msg' => 'invalid app'));
        }
    }

    //二维码
    public function antQrcode()
    {
        Vendor('phpqrcode.phpqrcode');
        $QRcode = new \QRcode();
        $url = C('SITE_URL') . '/Wap/Applications/ant';
        $level = 'L';
        $size = 4;
        $QRcode::png($url, false, $level, $size, 1);
    }

    //上传excel
    public function antExcel()
    {
        set_time_limit(0);
        $filename = './Public/Uploads/daily_sign/20180917/ant.xlsx';
        vendor('phpexcel.PHPExcel');
        $objReader = new \PHPExcel_Reader_Excel2007();
        $objExcel = $objReader->load($filename);

        $sheet = $objExcel->getSheet(0);                 // 读取第一个工作表
        $highestRow = $sheet->getHighestRow();           // 取得总行数
        $highestColumn = $sheet->getHighestColumn();     // 取得总列数

        $arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        // 一次读取一列
        $res_arr = array();
        for ($row = 2; $row <= $highestRow; $row++) {
            $row_arr = array();
            for ($column = 0; $arr[$column] != 'D'; $column++) {
                $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                $row_arr[] = $val;
            }
            $res_arr[] = $row_arr;
        }
        if ($res_arr) {
            $data = array();
            foreach ($res_arr as $value) {
                $data[$value[1]] = array(
                    'id' => $value[1],
                    'image' => '/Public/images/ant/P' . $value[1] . '.jpg',
                    'text' => $value[0],
                    'displayorder' => $value[1],
                    'type' => $value[2]
                );
            }
//            dump($data);exit;
            header("Content-Type: text/html; charset=utf-8");
            echo json_encode($data, JSON_UNESCAPED_UNICODE);
        } else {
            $this->error('上传文件不能为空，操作失败');
        }
    }

    //数据统计
    public function downloadAnt()
    {
        $file_path = './Public/json/ant.json';
        if (file_exists($file_path)) {
            $json_string = file_get_contents($file_path);
            $data = json_decode($json_string, true);
            if (!empty($data)) {
                foreach ($data as $value) {
                    $ids[] = $value['id'];
                    $list[] = array(
                        'id' => $value['id'],
                        'image' => C('SITE_URL') . $value['image']
                    );
                }
            }
        }
        $where["token"] = $this->wxTestToken;
        $where["pid"] = $this->_ant;
        $where["award_id"] = array('in', $ids);
        $where["status"] = 1;
        $record = M("redpacket_fansaward")->where($where)->field("id,award_id,zhongjiang")->select();
        $records = array();
        if (!empty($record)) {
            foreach ($record as $re) {
                if ($re['zhongjiang'] == 1) {
                    $records[$re['award_id']]['wx']++;
                } else {
                    $records[$re['award_id']]['ali']++;
                }
            }
        }
        if (!empty($list)) {
            foreach ($list as &$li) {
                $li['wx'] = isset($records[$li['id']]) ? $records[$li['id']]['wx'] : 0;
                $li['ali'] = isset($records[$li['id']]) ? $records[$li['id']]['ali'] : 0;
                $li['count'] = $li['wx'] + $li['ali'];
            }
        }
        if (!empty($list)) {
            set_time_limit(0);
            vendor('phpexcel.PHPExcel');
            $objExcel = new \PHPExcel();
            $objActSheet = $objExcel->getActiveSheet();
            $objActSheet->getColumnDimension('A')->setWidth(10);
            $objActSheet->getColumnDimension('B')->setWidth(50);
            $objActSheet->getColumnDimension('C')->setWidth(20);
            $objActSheet->getColumnDimension('D')->setWidth(20);
            $objActSheet->getColumnDimension('E')->setWidth(20);
            $objActSheet->setCellValue('A1', "PPT编号");
            $objActSheet->setCellValue('B1', "图片");
            $objActSheet->setCellValue('C1', "点赞数（微信）");
            $objActSheet->setCellValue('D1', "点赞数（支付宝）");
            $objActSheet->setCellValue('E1', "合计");
            $line = 2;
            foreach ($list as $value) {
                $objActSheet->setCellValue('A' . $line, $value['id']);
                $img = @imagecreatefromjpeg($value['image']);
                if ($img) {
                    $objDrawing = new \PHPExcel_Worksheet_MemoryDrawing();
                    $objDrawing->setImageResource($img);
                    $objDrawing->setHeight(120);
                    $objDrawing->setWidth(120);
                    $objDrawing->setCoordinates('B' . $line);
                    $objDrawing->setOffsetX(10);
                    $objDrawing->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT);
                    $objDrawing->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                    $objDrawing->setWorksheet($objActSheet);
                } else {
                    $objActSheet->setCellValue('B' . $line, '');
                }
                $objActSheet->setCellValue('C' . $line, $value['wx']);
                $objActSheet->setCellValue('D' . $line, $value['ali']);
                $objActSheet->setCellValue('E' . $line, $value['count']);
                $objActSheet->getRowDimension($line)->setRowHeight(80);
                $line++;
            }
            $fileName = '数据统计' . date('Ymd') . '.xlsx';
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
            $objWriter->save('php://output');
        }
    }
    //-------------------------------支付宝H5结束--------------------------------------

    //-------------------------------2018电子商务创新创业H5开始-------------------------
    public function dscycx2018()
    {
        header("Content-type: text/html; charset=utf-8");
        die('活动已结束！');
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {//微信端打开
            $code = I('get.code', -1);
            $openid = session('dscycx2018_openid');
            if ($code != -1) {
                if (!$openid) {
                    $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
                    $out = $wechat->snsapiUserInfo($this->wxTestUser['appid'], $this->wxTestUser['appsecret'], $code);
                    if ($out != null) {
                        session('dscycx2018_openid', $out['openid']);
                        session('dscycx2018_nickname', $out['nickname']);
                    }
                }
                $title = '“之江创客”赋能号宇宙飞船即将登陆杭州';
                $nickname = session('dscycx2018_nickname') ? session('dscycx2018_nickname') : '来宾';
                FactoryModel::viewPage(4);
                $count = FactoryModel::getVirtualNumber(4, 100);
                $number = $this->_dscycxNumber($count);
                $wxJSApi = WeixinService::buildWXJSApi($this->wxTestUser);
                $wxConfig = array(
                    'appId' => $this->wxTestUser['appid'],
                    'timestamp' => $wxJSApi['timestamp'],
                    'nonceStr' => $wxJSApi['noncestr'],
                    'signature' => $wxJSApi['sha1']
                );
                $wxShare = array(
                    'share_title' => '“之江创客”赋能号宇宙飞船即将登陆杭州',
                    'share_title2' => '您是第' . $count . '位登陆之江创客号的乘客',
                    'share_desc' => '2018全球电商双创大赛总决赛暨颁奖盛典启动，活动报名&最佳人气项目评选请入',
                    'share_image' => C('SITE_URL') . '/Public/images/share_cycx2018.png',
                    'share_link' => C('SITE_URL') . '/Wap/Applications/dscycx2018'
                );
                $this->assign('title', $title);
                $this->assign('nickname', $nickname);
                $this->assign('number', $number);
                $this->assign('count', $count);
                $this->assign('wxConfig', $wxConfig);
                $this->assign('wxShare', $wxShare);
                $this->display('Applications/dscycx2018/index');
            } else {
                if ($openid) {
                    $title = '“之江创客”赋能号宇宙飞船即将登陆杭州';
                    $nickname = session('dscycx2018_nickname') ? session('dscycx2018_nickname') : '来宾';
                    FactoryModel::viewPage(4);
                    $count = FactoryModel::getVirtualNumber(4, 100);
                    $number = $this->_dscycxNumber($count);
                    $wxJSApi = WeixinService::buildWXJSApi($this->wxTestUser);
                    $wxConfig = array(
                        'appId' => $this->wxTestUser['appid'],
                        'timestamp' => $wxJSApi['timestamp'],
                        'nonceStr' => $wxJSApi['noncestr'],
                        'signature' => $wxJSApi['sha1']
                    );
                    $wxShare = array(
                        'share_title' => '“之江创客”赋能号宇宙飞船即将登陆杭州',
                        'share_title2' => '您是第' . $count . '位登陆之江创客号的乘客',
                        'share_desc' => '2018全球电商双创大赛总决赛暨颁奖盛典启动，活动报名&最佳人气项目评选请入',
                        'share_image' => C('SITE_URL') . '/Public/images/share_cycx2018.png',
                        'share_link' => C('SITE_URL') . '/Wap/Applications/dscycx2018'
                    );
                    $this->assign('title', $title);
                    $this->assign('nickname', $nickname);
                    $this->assign('number', $number);
                    $this->assign('count', $count);
                    $this->assign('wxConfig', $wxConfig);
                    $this->assign('wxShare', $wxShare);
                    $this->display('Applications/dscycx2018/index');
                } else {
                    $wechat = new \Wap\Service\WechatService($this->wxTestUser['appid'], $this->wxTestUser['appsecret']);
                    $forward = C('SITE_URL') . '/Wap/Applications/dscycx2018?' . $_SERVER['QUERY_STRING'];
                    $url = $wechat->snsapiUserInfoLink($forward, $this->wxTestUser['appid']);
                    redirect($url);
                }
            }
        } else {//普通浏览器打开
            $title = '“之江创客”赋能号宇宙飞船即将登陆杭州';
            $nickname = '来宾';
            FactoryModel::viewPage(4);
            $count = FactoryModel::getVirtualNumber(4, 100);
            $number = $this->_dscycxNumber($count);
            $wxConfig = $wxShare = array();
            $this->assign('title', $title);
            $this->assign('nickname', $nickname);
            $this->assign('number', $number);
            $this->assign('count', $count);
            $this->assign('wxConfig', $wxConfig);
            $this->assign('wxShare', $wxShare);
            $this->display('Applications/dscycx2018/index');
        }
    }

    //序号
    private function _dscycxNumber($count)
    {
        if ($count < 10) {
            $number = '00000' . $count;
        } elseif ($count < 100) {
            $number = '0000' . $count;
        } elseif ($count < 1000) {
            $number = '000' . $count;
        } elseif ($count < 10000) {
            $number = '00' . $count;
        } elseif ($count < 100000) {
            $number = '0' . $count;
        } else {
            $number = $count;
        }
        $number = '2018' . $number;
        return $number;
    }

    //-------------------------------2018电子商务创新创业H5结束-------------------------

    //-------------------电子特刊市域治理---------------------
    public function dztk()
    {
        $wx = WeixinService::getWxuser($this->wxTestToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $this->assign('wxConfig', $wxConfig);
        $id = I("get.id", "", "");
        if (empty($id)) {
            $this->display('Applications/dztk/index_');
        } else {
            $this->display('Applications/dztk/index_' . $id);
        }
        return true;
    }
    //-------------------电子特刊市域治理---------------------

    //----------------美好生活品牌投票------
    public function mhshtp()
    {
        $wx = WeixinService::getWxuser($this->wxTestToken);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        $wxConfig = array(
            'appId' => $wx['appid'],
            'timestamp' => $wxJSApi['timestamp'],
            'nonceStr' => $wxJSApi['noncestr'],
            'signature' => $wxJSApi['sha1']
        );
        $this->assign('wxConfig', $wxConfig);
        $this->display('Applications/mhshtp');
    }

    //-------------------------------------

    public function tpchange()
    {
        $praise_id = I("get.praise_id", "", "");//-----投票活动ID-----
        $ograde = I("get.ograde", "", "");//----原始id----
        $rgrade = I("get.rgrade", "", "");//----目标id-------------
        $add = I("get.add", "", "");//------编号增加量-------
        $g = I("get.g", "", "");//------需要设置的编号----------
        $r = I("get.r", "", "");//------连续的个数----------------
        if (empty($ograde) || empty($praise_id)) {
            return true;
        }
        if (!empty($rgrade)) {//---------两者编号对调-----------
            $cond_ori['grade'] = $rgrade;
            $cond_ori['status'] = 1;
            $cond_ori['praise_id'] = $praise_id;
            $item_ori = M("praise_item")->where($cond_ori)->find();

            $cond_des['grade'] = $rgrade;
            $cond_des['status'] = 1;
            $cond_des['praise_id'] = $praise_id;
            $item_des = M("praise_item")->where($cond_des)->find();

            if (!empty($item_ori) && !empty($item_des)) {
                $cond_ori_save['id'] = $item_ori['id'];
                $data_ori['id'] = $item_ori['id'];
                $data_ori['grade'] = $rgrade;
                M("praise_item")->where($cond_ori_save)->save($data_ori);

                $cond_des_save['id'] = $item_des['id'];
                $data_des['id'] = $item_des['id'];
                $data_des['grade'] = $ograde;
                M("praise_item")->where($cond_des_save)->save($data_des);
            }
            return true;
        }
        if (!empty($g)) {
            $cond_ori['grade'] = $ograde;
            $cond_ori['status'] = 1;
            $cond_ori['praise_id'] = $praise_id;
            $item_ori = M("praise_item")->where($cond_ori)->find();
            if (!empty($item_ori)) {
                $cond_ori_save['id'] = $item_ori['id'];
                $data['grade'] = $g;
                $data['id'] = $item_ori['id'];
                M("praise_item")->where($cond_ori_save)->save($data);
            }
            return true;
        }
        if (!empty($add) && !empty($r)) {
            $cond_ori['grade'] = $ograde;
            $cond_ori['status'] = 1;
            $cond_ori['praise_id'] = $praise_id;
            $item_ori = M("praise_item")->where($cond_ori)->find();
            var_dump($item_ori);
            if (!empty($item_ori)) {
                $cond['praise_id'] = $item_ori['praise_id'];
                $bet_ori = $item_ori['grade'];
                $bet_des = $item_ori['grade'] + $r - 1;
                $cond['grade'] = array("between", array($bet_ori, $bet_des));
                M("praise_item")->where($cond)->setInc("grade", $add);
            }
            return true;
        }
    }

}
